开发者

Whenever a User object is created, create UserInfo object too

Whenever a User object is created, I want a UserInfo object to be created too, and linked to it.

Unfortunately this does not create any UserInfo:

class User <开发者_如何转开发; ActiveRecord::Base
  has_one :user_info
  ...

  def init
    self.user_info = user_info
    self.save!
  end

Why is the init method not called? How to reach my goal?


sombe's technique is right, but his details aren't ideal. In fact, since create_user_info is already a method on User instances, all you want is something like:

class User < ActiveRecord::Base
  has_one :user_info
  before_create :create_user_info
end

Edit: init doesn't do anything particularly magical under Rails (I... don't think it does under basic Ruby either - are you thinking of initialize? I'll assume you are). initialize is fired off when an instance of the Ruby class is created in memory. That's divorced by quite some margin from an instance of the model being created in the database; a new class instance could be due to you calling build (and not saving yet), or even due to reading an instance out of the database.

If you want to step in on database operations, you need to make use of the ActiveRecord callbacks. You might find my answer to this question useful.


before_save callback triggers on create and update. I'd suggest to use after_create because before_create can return errors

class User < ActiveRecord::Base
  has_one :user_info
  ...

  after_create do
    create_user_info
end


In your User model, use a before_save filter instead of init like this:

before_save :create_user_info

...

private

def create_user_info 
   user_info = UserInfo.new
   if user_info.save
       self.user_info_id = user_info.id
   end
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜