[英]Polymorphic association and nested attributes
我有一個產品模型和一個圖像模型(基於回形針)。
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
但這並沒有改變任何東西,我總是有相同的錯誤消息。 您是否知道權限問題來自何處?
您可能需要更改
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])
您定義了一個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個文件字段。
任何可能與您的file_field
<%= images_form.file_field :image %>
而不是以下內容?
<%= images_form.file_field :picture %>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.