我在嵌套属性中使用回形针,我不确定我遗漏了什么。表单上的视图缺少文件上载选项。
类型
<%= form_with(model: news, local: true, html: { multipart: true } ) do |form| %>
<%= form.fields_for :images do |img| %>
<%= img.file_field :img, multiple: true %>
<% end%>
<% end %>
class News < ApplicationRecord
has_many :images, dependent: :destroy
accepts_nested_attributes_for :images, allow_destroy: true
end
class Image < ApplicationRecord
belongs_to :news
has_attached_file :img, :styles => { :show => "600x600>" }, size: { less_than: 2.megabytes }
validates_attachment_content_type :img, :content_type => ["image/jpg", "image/jpeg", "image/gif", "image/png"]
end
控制器
class NewsController < ApplicationController
def new
@news = News.new
@news.images.build
end
def create
@news = News.new(news_params)
respond_to do |format|
if @news.save
format.html { redirect_to @news, notice: 'News was successfully created.' }
format.json { render :show, status: :created, location: @news }
else
format.html { render :new }
format.json { render json: @news.errors, status: :unprocessable_entity }
end
end
end
private
def set_news
@news = News.find(params[:id])
end
def news_params
params.require(:news).permit(:title, :description, :category, images_attributes: [:id, :img, :news_id, :_destroy])
end
end
如果我改变
:images
到
:image
在表单中,该字段出现,但在提交时出现错误:
Unpermitted parameter: :image