【发布时间】:2012-01-08 10:09:24
【问题描述】:
我有一个项目资源和一个所有者资源。
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
我的问题是我无法创建引用现有 Owner 对象的新 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 对象。
我找到了这些链接,但无法确定这是 Rails 中的功能还是错误:
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
有人可以告诉我如何进行这项工作,还是我误解了使用“accepts_nested_attributes_for”的正确方法??
我正在使用 Rails 3.0.5 和 Ruby 1.9.2p0。
提前致谢。
【问题讨论】:
标签: ruby-on-rails nested-attributes