我有這樣的事情:如何在ActiveRecord中設置has_one默認值?
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?
。
我正想着這些,但實際上我specifi c的情況下,profile類取決於子類:'class Admin
2010-09-19 01:05:41