我有两种模式:
User
(电子邮件:字符串)
Profile
(姓名:字符串)
class User < ActiveRecord::Base
has_one :profile
delegate :name, :name=, :to => :profile
end
class Profile < ActiveRecord::Base
belongs_to :user
end
rails c
u = User.new
u.build_profile #=> init Profile
u.name = 'foo'
u.email = 'some@ema.il'
u.save #=> both User and Profile are saved
u.name = 'bar'
u.save #=> true, but changes in Profile were not saved!
u.email = 'new@ema.il'
u.save #=> true, new User email was saved, Profile - still not!
u.name #=> 'bar', but in database it's 'foo'
为什么没有更新配置文件(仅首次保存)?如何解决这个问题?
答案 0 :(得分:11)
ArcaneRain,您应该在关系中添加“自动保存”选项,而不是为此添加回调:
has_one :profile, :autosave => true
你还应该调查'依赖'选项。 更多信息: http://guides.rubyonrails.org/association_basics.html#has_one-association-reference
答案 1 :(得分:1)
这个问题看起来很熟悉:)
试过这个并且它有效:
after_save :save_profile, :if => lambda {|u| u.profile }
def save_profile
self.profile.save
end
旁注:
如果您经常使用这两种型号,我建议您添加一些default scope以始终在profile
上加载user
。