ruby-on-rails - 多态关联和嵌套属性

标签 ruby-on-rails paperclip ruby-on-rails-4 polymorphic-associations

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

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

因此,我在许可产品参数中添加了图像属性 ( like there ):

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

但这并没有改变任何东西,我总是有相同的错误消息。您知道权限问题从何而来吗?

最佳答案

您可能需要更改

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])

关于ruby-on-rails - 多态关联和嵌套属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18381757/

相关文章:

javascript - 您在 Rails 应用程序中使用什么 Web UI 工具包?

ruby-on-rails - 使用Rails接收电子邮件(ActionMailer)以处理图像附件

ruby-on-rails - Heroku +回形针+ Amazon S3-定价?

ruby-on-rails - Rails form_for 多个不同的类对象?

ruby-on-rails - Rails 4.1 计数器缓存不更新

ruby-on-rails - 如何使用 Ruby 1.8.7 在 Thinking sphinx 中索引 bool 列

ruby-on-rails - Rails 嵌套资源未知属性错误

ruby-on-rails - Mongodb 查询说 "wrong number of arguements (2 for 1)"

ruby-on-rails - rails 4 设计带有回形针,未定义的方法 after_commit

ruby-on-rails - unicorn 服务时,Rails 为预编译 Assets 生成错误的指纹