嵌套属性中缺少文件字段

时间:2021-06-22 23:00:28

I'm using paperclip in nested attributes and I'm not sure what I'm missing. The view on the form is missing the file upload option.

我在嵌套属性中使用回形针,我不确定我缺少什么。表单上的视图缺少文件上载选项。

Form

形成

<%= 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 %>

Models

楷模

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

Controller

调节器

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

If I change :images to :image in the form the field appears, but then gives an error on submission:

如果我更改:图像到:图像显示字段,但随后在提交时出错:

Unpermitted parameter: :image

1 个解决方案

#1


1  

In your case, you need to explicitly pass a record_object to the fields_for

在您的情况下,您需要将record_object显式传递给fields_for

<%= form.fields_for :images, @news.images.build do |img| %>
  <%= img.file_field :img, multiple: true %>
<% end%>

Also in order to send multiple values for img, it should be an array in the permitted params. You should change the news_params to below

另外,为了发送img的多个值,它应该是允许的参数中的数组。您应该将news_params更改为以下

def news_params
  params.require(:news).permit(:title, :description, :category, images_attributes: [:id, :news_id, :_destroy, img: []])
end

#1


1  

In your case, you need to explicitly pass a record_object to the fields_for

在您的情况下,您需要将record_object显式传递给fields_for

<%= form.fields_for :images, @news.images.build do |img| %>
  <%= img.file_field :img, multiple: true %>
<% end%>

Also in order to send multiple values for img, it should be an array in the permitted params. You should change the news_params to below

另外,为了发送img的多个值,它应该是允许的参数中的数组。您应该将news_params更改为以下

def news_params
  params.require(:news).permit(:title, :description, :category, images_attributes: [:id, :news_id, :_destroy, img: []])
end