使用Paperclip在嵌套属性中未允许的参数

时间:2017-08-21 07:00:30

标签: ruby-on-rails

我希望通过rails 5中的嵌套属性使用回形针添加多个图像。

我不确定我错过了什么,但是引用以下错误引用了这些属性:

Unpermitted parameter: :image

我在新闻控制器属性中引用了图像属性,请参见下文。图像不会保存到数据库中。

模型

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 :image, :styles => { :show => "600x600>" }, size: { less_than: 2.megabytes }
  validates_attachment_content_type :image, :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, :image, :news_id, :_destroy])
    end
end

表格

<%= form.fields_for :image do |img| %>
   <%= img.file_field :image, multiple: true %>
<% end%>

已发送结果

 Parameters: {"utf8"=>"✓", "authenticity_token"=>"kFPv2dZE6J9uHi4pu1qM+ZgDwXbFadjD2KjlhmLmk7LosumgB0vWQWA6zPJRe0b38JSSUZHYKRd4G6XAYEgmwA==", "news"=>{"title"=>"News Title", "description"=>"Random text goes in here.", "category"=>"", "image"=>{"image"=>#<ActionDispatch::Http::UploadedFile:0x007feed58a5ba8 @tempfile=#<Tempfile:/var/folders/n1/dt5dwx0n7rx59_3bpvp64x400000gp/T/RackMultipart20170822-995-firof5.jpg>, @original_filename="03.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"news[image][image]\"; filename=\"03.jpg\"\r\nContent-Type: image/jpeg\r\n">}}, "commit"=>"Update News", "id"=>"1-news-title"}

2 个答案:

答案 0 :(得分:2)

  

未经许可的参数:: image

由于您有form.fields_for :images,因此您应该form.fields_for :image而不是<%= form.fields_for :images do |img| %> <%= img.file_field :image, multiple: true %> <% end%>

record_object

<强>更新

在这种情况下,您需要明确地将fields_for传递给<%= form.fields_for :images, @news.images.build do |img| %> <%= img.file_field :image, multiple: true %> <% end%>

news_params

另外,为了发送图像的多个值,它应该是允许的参数中的数组。您应该将def news_params params.require(:news).permit(:title, :description, :category, images_attributes: [:id, :news_id, :_destroy, image: []]) end 更改为

this.setState({})

答案 1 :(得分:0)

从您的表单中,我可以看到您没有以适当的格式向控制器发送参数。

您的参数应包含images_attributes而不是image

更改

<%= form.fields_for :image do |img| %>
   <%= img.file_field :image, multiple: true %>
<% end%>

<%= form.fields_for :images_attributes do |img| %>
   <%= img.file_field :image, multiple: true %>
<% end%>