【问题标题】:Image(#70365286921100) expected, got Array(#70365535770260) error预期图像(#70365286921100),得到数组(#70365535770260)错误
【发布时间】:2012-05-03 17:04:59
【问题描述】:

我正在尝试创建一个简单的 rails 3.2 应用程序。

为简单起见,该应用有两个模型:产品和图像

产品应该有很多图片,所以这是我的模型:

class Product < ActiveRecord::Base
  has_many :images, :class_name => 'Image'
end

class Image < ActiveRecord::Base
  belongs_to :product
  has_attached_file :image, :styles => { :normal => "300x300", :small => "70x70" }
end

我正在使用 active_admin,这是我创建产品的表单:

  <%= semantic_form_for [:admin, @product], :html => {:multipart => true} do |f| %>

    <%= f.inputs :title, :description, :price %>

    <%= f.semantic_fields_for :images do |f2| %>
        <%= f2.file_field :image %>
    <% end %>

    <%= f.buttons :commit %>
  <% end %>

当我提交表单时,出现以下异常:

Image(#70365286921100) expected, got Array(#70365535770260)

{"utf8"=>"✓",
 "authenticity_token"=>"waFPhUIJPD90r5SRVmvvYBEcpZHgFJbM325wZDknWf8=",
 "product"=>{"title"=>"rfrfrf",
 "description"=>"rfrfr",
 "price"=>"200.99",
 "images"=>{"image"=>#<ActionDispatch::Http::UploadedFile:0x007ffe63d19e58 @original_filename="IMG_0097.JPG",
 @content_type="image/jpeg",
 @headers="Content-Disposition: form-data; name=\"product[images][image]\"; filename=\"IMG_0097.JPG\"\r\nContent-Type: image/jpeg\r\n",
 @tempfile=#<File:/var/folders/_j/s1n6_4551cxc765p1zm8w54r0000gq/T/RackMultipart20120503-2609-bwvbis>>}},
 "commit"=>"Create Product"}

为什么会这样?谁能帮帮我?

提前致谢!

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3.2


    【解决方案1】:

    我相信您的产品模型中需要accepts_nested_attributes_for :images。 Product 模型应如下所示:

    class Product < ActiveRecord::Base
      has_many :images, :class_name => 'Image'
      accepts_nested_attributes_for :images
    end
    

    如果您查看您的参数哈希,您会看到:

    "images"=>{"image"=> ...
    

    accepts_nested_attributes_for 所做的是更改参数的结构以适应 has_many :images 关联指定的一对多关系。

    假设表单中有多个图像,您的参数哈希将包含:

    "images_attributes"=>{"0"=>{"image"=> ...  }, "1"=>{"image" => ... }, ...}
    

    另外,如果@product 是新的,请确保在到达视图之前致电@product.images.build

    【讨论】:

      猜你喜欢
      • 2021-05-14
      • 2021-12-28
      • 1970-01-01
      • 2021-12-29
      • 1970-01-01
      • 2018-07-05
      • 1970-01-01
      • 2018-08-26
      • 2019-03-28
      相关资源
      最近更新 更多