gpt4 book ai didi

ruby-on-rails - Rails 委托(delegate)更新调用

转载 作者:行者123 更新时间:2023-12-04 06:07:33 24 4
gpt4 key购买 nike

我有两个模型: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'

为什么个人资料没有更新(仅第一次保存)?如何解决这个问题?

最佳答案

ArcaneRain,您应该在您的关系中添加“自动保存”选项,而不是为此添加回调:
has_one :profile, :autosave => true
您还应该调查“依赖”选项。
更多信息在这里:
http://guides.rubyonrails.org/association_basics.html#has_one-association-reference

关于ruby-on-rails - Rails 委托(delegate)更新调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9228634/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com