嵌套属性中缺少文件字段

时间:2017-08-22 03:50:09

标签: ruby-on-rails

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

表格

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

1 个答案:

答案 0 :(得分:1)

在您的情况下,您需要明确地将ng serve传递给record_object

fields_for

同样为了发送<%= form.fields_for :images, @news.images.build do |img| %> <%= img.file_field :img, multiple: true %> <% end%> 的多个值,它应该是允许的参数中的数组。您应该将img更改为

news_params