2016-03-01 71 views
-1

之间的关联时,我完全被卡住的东西,似乎应该是这么简单。我有一个订阅模式,可以创建与帐户模型的关联。这部分工作正常使用:通行证用户ID创建其他两款车型

after_create :create_account 

我想要的是将用户传递到帐户记录,理想情况下作为account_manager。我也有一个user_id字段,但我更喜欢使用account_manager_id。我可以手动做到这一点,但让它自动发生让我绊倒。我尝试了多种方法,通过在创建帐户控制器中添加各种选项,将当前用户传入帐户。到目前为止没有运气。有没有人有任何想法?

@account = Account.new(params[:account].merge(account_manager_id: current_owner)) 


@user = current_user 
@account = @user.accounts.create(params[:account]) 


@account = Account.new(account_params) 
@account.account_manager = current_user 


@account = current_user.accounts.build(params[:account]) 

我的帐户控制器

class AccountsController < ApplicationController 

    def index 
    @accounts = Account.all 
    end 

    def show 
    @account = Account.find(params[:id]) 
    end 

    def new 
    @account = Account.new 
    end 

    def edit 
    @account = Account.find(params[:id]) 
    end 

    def create 
    @account = Account.new(account_params) 
    @account.account_manager = current_user 
     if @account.save 
     flash[:success] = "Content Successfully Created" 
     redirect_to @account 
     else 
     render 'new' 
    end 
    end 

    def update 
    @account = Account.find(params[:id]) 
     if @account.update(account_params) 
     flash[:success] = "Your account was successfully updated" 
     redirect_to current_user 
     else 
     render 'edit' 
    end 
    end 

    def destroy 
    @account = Account.find(params[:id]) 
    @account.destroy 
    respond_to do |format| 
     flash[:info] = "The grant was successfully destroyed" 
    end 
    end 

    private 

    # Never trust parameters from the scary internet, only allow the white list through. 
    def account_params 
     params.require(:account).permit(:name, :user_id, :account_manager_id,:subscription_id) 
    end 
end 

account.rb

class Account < ActiveRecord::Base 
    has_and_belongs_to_many :users 
    belongs_to :account_manager, :class_name => 'User', :foreign_key => 'account_manager_id' 
    belongs_to :subscription, :dependent => :destroy 
end 

user.rb

class User < ActiveRecord::Base 
    has_one :subscription 
    has_and_belongs_to_many :account 

subscription.rb

class Subscription < ActiveRecord::Base 
    include Koudoku::Subscription 

    has_one :account 
    belongs_to :user 
    belongs_to :coupon 
    after_create :create_account #after a subscription is created, automatically create an associtaed account 

end 
+0

提供的车型代码和控制器进行审查。 – Dharam

+0

您是否收到错误?如果是这样,请发帖。此外,你在几个地方拼写“经理”错误(“经理”)。 – jvillian

+0

啊,很好的抓住了“经理人”。我在创建订阅时没有在网站上发现任何错误。但是当我检查Account.all account_manager_id和user_id都是零。 – railsie

回答

0

掏出

after_create :create_account 

,并增加了以下

# subscriptions_controller.rb 
def create 
    ... 
    if @subscription.save 
    @subscription.create_account(account_manager: current_user) 
    end 
end