Reputation: 181
I have an application where a user adds a subscription and an account is automatically created for that subscription. I also want to pass the current user to the account model as the account_manager. So far I have:
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
This works fine for the first user obviously but any attempts I've made to pass current_user, self, params, etc fails. Also when I use the def method the subscription ID is no longer passed to the account. I tried passing the current user through the AccountController but nothing happens. In fact I can still create an account if my AccountController is completely blank. Is after_create the best way to create an associated account and how do I pass the user to the account model? Thanks!
Upvotes: 0
Views: 1033
Reputation: 802
If you are using devise, you can do this directly in the controller with the current_user helper without a callback:
# subscriptions_controller.rb
def create
...
if @subscription.save
@subscription.create_account(account_manager: current_user)
end
end
Upvotes: 1