【发布时间】:2016-02-22 03:46:53
【问题描述】:
我有这样的事情:
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
这样,每当您最终create 用户时,您都将拥有个人资料。否则,唯一的情况是new_record?。
【问题讨论】:
标签: ruby-on-rails ruby activerecord