Rails中嵌套表单上的未知属性

时间:2010-07-02 17:23:38

标签: ruby-on-rails activerecord nested-forms

我无法让我的InventoryItem接受奇怪的嵌套属性。

在我的脚本/控制台中,我执行了以下操作:

>> InventoryItem.create!(:name => 'what', :image_attributes => [ {:image => File.open("/home/davidc/Desktop/letterbx.jpg", "r") }])
ActiveRecord::UnknownAttributeError: unknown attribute: image_attributes

我不知道为什么我在模型中遇到未知属性错误,我已经做了accept_nested_attributes。

我正在使用Rails v2.3.5。

库存物料模型

class InventoryItem < ActiveRecord::Base
  uuid_it

  belongs_to :user
  has_many :orders
  has_many :images, :validate => true
  accepts_nested_attributes_for :images
end

图像

class Image < ActiveRecord::Base
  belongs_to :inventory_item

  has_attached_file :image, :style => { :medium => "300x300>", :thumb => "100x100>" }
end

2 个答案:

答案 0 :(得分:2)

你有has_many :images 因此,它应该是:images_attributes,而不是:image_attributes

InventoryItem.create!(:name => 'what', :images_attributes => [ {:image => File.open("/home/davidc/Desktop/letterbx.jpg", "r") }])

当你有has_many关系

时,使用哈希数组是正确的

答案 1 :(得分:0)

:image_attributes应该是哈希值。

InventoryItem.create!(
   :name => 'what',
   :image_attributes => { ... }
)