2016-03-07 37 views
0

我有一个应用程序,用户添加一个订阅并为该订阅自动创建一个帐户。我也想将当前用户作为account_manager传递给帐户模型。到目前为止,我有:使用after_create方法时传递参数Rails

class Subscription < ActiveRecord::Base 
    has_one :account 
    after_create :create_account #after a subscription is created, automatically create an associated account 

    def create_account 
    Account.create :account_manager_id => "1" #need to modify this to get current user 
    end 
end 



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

这第一个用户正常工作明显,但我所做的任何企图通过CURRENT_USER,自我,则params,等失败。另外,当我使用def方法时,订阅ID不再传递给该帐户。我试图通过AccountController传递当前用户,但没有任何反应。事实上,如果我的AccountController是完全空白的,我仍然可以创建一个帐户。是after_create创建关联帐户的最佳方式,以及如何将用户传递给帐户模型?谢谢!

回答

1

如果使用的是设计,你可以与CURRENT_USER辅助控制器直接做这没有一个回调:

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

我不使用色器件但这非常完美!谢谢! – railsie