使用 after_create 方法 Rails 时传递参数
Passing params when using after_create method Rails
我有一个应用程序,用户在其中添加订阅并自动为该订阅创建一个帐户。我还想将当前用户作为 account_manager 传递给帐户模型。到目前为止我有:
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、self、params 等的任何尝试都失败了。此外,当我使用 def 方法时,订阅 ID 不再传递给该帐户。我尝试通过 AccountController 传递当前用户,但没有任何反应。事实上,如果我的 AccountController 完全空白,我仍然可以创建一个帐户。 after_create 是创建关联帐户的最佳方式吗?如何将用户传递给帐户模型?谢谢!
如果您使用的是 devise,您可以直接在控制器中使用 current_user 帮助器执行此操作,无需回调:
# subscriptions_controller.rb
def create
...
if @subscription.save
@subscription.create_account(account_manager: current_user)
end
end
我有一个应用程序,用户在其中添加订阅并自动为该订阅创建一个帐户。我还想将当前用户作为 account_manager 传递给帐户模型。到目前为止我有:
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、self、params 等的任何尝试都失败了。此外,当我使用 def 方法时,订阅 ID 不再传递给该帐户。我尝试通过 AccountController 传递当前用户,但没有任何反应。事实上,如果我的 AccountController 完全空白,我仍然可以创建一个帐户。 after_create 是创建关联帐户的最佳方式吗?如何将用户传递给帐户模型?谢谢!
如果您使用的是 devise,您可以直接在控制器中使用 current_user 帮助器执行此操作,无需回调:
# subscriptions_controller.rb
def create
...
if @subscription.save
@subscription.create_account(account_manager: current_user)
end
end