我有一個項目資源和一個所有者資源。如何創建引用現有嵌套屬性的新對象?
rails g scaffold Item name:string
rails g scaffold Owner name:string
class Item < ActiveRecord::Base
has_one :owner
accepts_nested_attributes_for :owner
end
class Owner < ActiveRecord::Base
belongs_to :item
end
我的問題是我無法創建一個引用現有所有者對象的新Item對象。
In /db/migrate/create_owners.rb
def self.up
...
t.integer :item_id
end
rake db:migrate
rails c
ruby-1.9.2-p0 > o= Owner.create(:name => "Test")
=> #<Owner id: 1, name: "Test", created_at: "...", updated_at: "...">
ruby-1.9.2-p0 > i= Item.create(:owner_attributes => {"id" => Owner.last.id.to_s})
ActiveRecord::RecordNotFound: Couldn't find Owner with ID=1 for Item with ID=
我知道Item.create(:owner_id => "1")
會在這種情況下工作,但不幸的是這不是我的應用程序一個可行的解決方案。這是因爲我正在動態添加和刪除嵌套屬性,例如,需要創建一個具有一個現有Owner對象和一個新Owner對象的新Item對象。
我發現這些鏈接,但不能工作了,如果這是一個功能或在軌道中的錯誤:
https://rails.lighthouseapp.com/projects/8994/tickets/4254-assigning-nested-attributes-fails-for-new-object-when-id-is-specified
http://osdir.com/ml/RubyonRails:Core/2011-05/msg00001.html
有人可以給我一個想法,我怎樣才能使這項工作或我誤解了正確的方法來使用'accepted_nested_attributes_for'?
我使用Rails 3.0.5和Ruby 1.9.2p0。
在此先感謝。
謝謝!我從未參與過這個項目一年多,但你的回答是有道理的。當我有一點時,我會嘗試(出於興趣)。 – 2014-01-21 09:48:52