2

我有一个产品模型和一个图像模型(基于回形针)。

class Product < ActiveRecord::Base
  has_many :images, as: :imageable,
                    dependent: :destroy
  accepts_nested_attributes_for :images
end

class Image < ActiveRecord::Base
  belongs_to :imageable, polymorphic: true
  has_attached_file :picture
end

我想在创建产品的同一页面中为我的产品添加图像 ( /products/new)。这是表格:

<%= form_for(@product, html: { multipart: true}) do |f| %>
  <%= render 'shared/error_messages', object: f.object %>
  <div>
    <%= f.label :name, t('product.name') %>
    <%= f.text_field :name %>
  </div>                    
  <div class="file_field">
     <%= f.fields_for :image do |images_form| %>
       <%= images_form.file_field :image %>
     <% end %>
  </div>
  <%= f.submit @submit_button %>
<% end %>

然后我转到/products/new页面,填写字段,然后单击提交按钮。服务器尝试渲染产品的展示页面,但由于图像尚未保存,因此无法正常工作。我有以下错误:

undefined method `picture' for nil:NilClass

对于产品展示页面中的以下行

image_tag(@product.images.first.picture.url(:medium))

我想知道为什么没有保存图像,我看到服务器呈现以下消息:

Unpermitted parameters: images_attributes

所以我在许可产品参数中添加了图像属性(就像那里一样):

def product_params
  params.require(:product).permit(:name, :sharable, :givable, image_attributes: [:name, :picture_file_name, :picture_content_type, :picture_file_size])
end

但这并没有改变任何东西,我总是有同样的错误信息。您知道权限问题来自哪里吗?

4

3 回答 3

4

你可能需要改变

params.require(:product).permit(:name, :sharable, :givable, image_attributes: [:name, :picture_file_name, :picture_content_type, :picture_file_size])

params.require(:product).permit(:name, :sharable, :givable, images_attributes: [:name, :picture])
于 2013-08-25T13:23:35.097 回答
1

您定义了一个 has_many 关联,因此在您看来,它应该是 f.fields_for :images

<%= f.fields_for :images do |images_form| %>
    <div class="file_field">         
       <%= images_form.file_field :picture %>         
    </div>
<% end %>

在您的控制器中,您应该首先构建一些图像并将您的 images_attributes 添加到允许的参数中。

@product = Product.new
3.times {@product.images.build}

您的视图将显示 3 个文件字段。

于 2013-08-22T14:34:50.910 回答
0

任何与你的file_field存在有关的机会

<%= images_form.file_field :image %>

而不是以下?

<%= images_form.file_field :picture %>
于 2013-08-23T08:04:43.503 回答