I have the following classes 开发者_如何学Goin a Rails 3.1.rc4
class User < ActiveRecord::Base
belongs_to :team
end
class Team < ActiveRecord::Base
has_many :users
end
What I'd like to do is create an associated team every time a user signs up using an activerecord callback. Something like this:
# in the User class
before_create {|user| user.create_team(name: "#{self.name}'s Team") }
However this doesn't seem to work properly. When I go to the rails console
to check it, I can create a user and type user.team
and I get a team as expected. However, if I do user.reload
and user.team
again, I get nil
.
How do I get the user to properly associate with the team?
Turns out 3.1.rc4 actually has a bug which prevents user.create_team
from working properly. See the issue on the rails github. A fix has been pushed so I guess it will be fixed in the next RC.
You need to do this with an after save because the id is not set until the user is saved. Rails won't let this record save because the associated record, the user model, has not been saved and does not have an id.
So you should do this:
class User < ActiveRecord::Base
belongs_to :team
after_create add_team_to_user
def add_team_to_user
Team.create({:user => self, :name => "#{name}'s Team"})
end
end
Or to prevent mass-asignment:
def add_team_to_user
self.team.create({:user => self, :name => "#{name}'s Team"})
end
精彩评论