我有父項和子項模型關係。在孩子的migration.rb中,子模型的每個列都有默認值(parent_id列除外)。Ruby on Rails:在創建父項時使用默認值創建子項
當我創建一個新的父對象時,如何創建一個子對象並將其與parent_id一起使用默認值的數據保存到表中?
我在想,它將不得不在母模型上使用類似after_create
的東西,但我不知道如何設置它。
我有父項和子項模型關係。在孩子的migration.rb中,子模型的每個列都有默認值(parent_id列除外)。Ruby on Rails:在創建父項時使用默認值創建子項
當我創建一個新的父對象時,如何創建一個子對象並將其與parent_id一起使用默認值的數據保存到表中?
我在想,它將不得不在母模型上使用類似after_create
的東西,但我不知道如何設置它。
修訂:我修改了使用before_create和構建,而不是創建相關模型的答案。 ActiveRecord機器會在保存父項時負責保存相關模型。
我甚至測試過這個代碼!
# in your Room model...
has_many :doors
before_create :build_main_door
private
def build_main_door
# Build main door instance. Will use default params. One param (:main) is
# set explicitly. The foreign key to the owning Room model is set
doors.build(:main => true)
true # Always return true in callbacks as the normal 'continue' state
end
####### has_one case:
# in your Room model...
has_one :door
before_create :build_main_door
private
def build_main_door
# Build main door instance. Will use default params. One param (:main) is
# set explicitly. The foreign key to the owning Room model is set
build_door(:main => true)
true # Always return true in callbacks as the normal 'continue' state
end
加...
構建方法是由的has_many聲明所屬模型的機械加。由於該示例使用has_many:門(型號名稱Door),構建調用爲doors.build
請參閱docs for has_many和has_one以查看所有添加的其他方法。
# If the owning model has
has_many :user_infos # note: use plural form
# then use
user_infos.build(...) # note: use plural form
# If the owning model has
has_one :user_info # note: use singular form
# then use
build_user_info(...) # note: different form of build is added by has_one since
# has_one refers to a single object, not to an
# array-like object (eg user_infos) that can be
# augmented with a build method
Rails 2.x引入了關聯的自動保存選項。我不認爲它適用於上述(我使用默認值)。 Autosave testing results.
你沒有指定(或我重讀它)你使用的是什麼樣的關係。如果您使用的是一對一關係,比如「has_one」,那麼創建將無法正常工作。在這種情況下,你必須使用這樣的事情:
在parent.rb
has_one :child
before_create {|parent| parent.build_child(self)}
after_create可能工作爲好,還沒有測試這一點。
而在child.rb
belongs_to :parent
我用這個頗有幾分以我現在的應用程序建立用戶模型時掙扎。
http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html 你可以看到HAS_ONE不支持parent.build或parent.create
希望這有助於。我自己是Ruby的新手,並慢慢開始穿越紅寶石叢林。一個不錯的旅程,但很容易迷路。:)
我的例子中的孩子模型被稱爲「user_info」,當我嘗試做'user_info.create(:main => true)'它錯誤,並說'未定義方法'創建'爲nil:NilClass' – Reti 2010-08-17 04:11:53
實際上,該模型在技術上稱爲'userInfo' – Reti 2010-08-17 04:14:37
嘗試'UserInfo.create' – zetetic 2010-08-17 08:01:34