gpt4 book ai didi

ruby-on-rails - 如何在 ActiveRecord 中设置 has_one 默认值?

转载 作者:数据小太阳 更新时间:2023-10-29 08:41:29 24 4
gpt4 key购买 nike

我有这样的东西:

class User < ActiveRecord::Base
has_one :profile
end

class Profile < ActiveRecord::Base
belongs_to :user
end

user = User.new
user.profile.something #=> ERROR

在这种情况下,设置默认配置文件对象的正确方法是什么?我试过这个:

class User < ActiveRecord::Base
default_scope :include => :profile
has_one :profile

def after_initialize
self.profile ||= Profile.new(:user => self)
end
end

...但这会创建 N+1 个查询。有什么想法吗?

更新

这就是我现在拥有的,工作正常,仍在寻找更好的东西:

class User < ActiveRecord::Base
default_scope :include => :profile
has_one :profile, :autosave => true

def after_initialize
self.profile = Profile.new(:user => self) if new_record?
end
end

这样,无论何时您最终创建您的用户,您都将拥有一个配置文件。否则,唯一的情况是 new_record?

最佳答案

您可以编写自己的 User#profile,如果它不存在,将为您构建一个:

class User < ActiveRecord::Base
has_one :profile

def profile_with_default
profile_without_default || build_profile
end
alias_method_chain :profile, :default
end

关于ruby-on-rails - 如何在 ActiveRecord 中设置 has_one 默认值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3742705/

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