Reputation: 483
I'm trying to create a resource Mission
when a new user is signed up. Mission has a foreign key Location
as well.
class User < ApplicationRecord
after_create :create_mission
private
def create_mission
Mission.create(user: self, location_id: 1, name: 'Mission 1')
end
end
But this code doesn't work unfortunately. How can I solve it?
Upvotes: 0
Views: 84
Reputation: 754
I do not recommend you to create relations in callbacks. It will hurt you if you will need to create user in another action or in console. Better to create it in controller after creation (in some service object in the future)
def create
if @user.save
@user.missions.create(...)
end
end
And you can use debugger to check errors dynamically (shipped with rails https://github.com/deivid-rodriguez/byebug, just insert 'debugger' in your code), probably you have some validation error.
Upvotes: 1
Reputation: 3339
How about this:
class User < ApplicationRecord
after_create :create_mission
private
def create_mission
missions.create! location_id: 1, name: 'Mission 1'
end
end
Now your error could be visible with create!
. Try this.
Upvotes: 1