代码之家  ›  专栏  ›  技术社区  ›  DollarChills

嵌套属性中缺少文件字段

  •  0
  • DollarChills  · 技术社区  · 9 年前

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

    类型

    <%= 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 回复  |  直到 9 年前
        1
  •  1
  •   Pavan Cesar    9 年前

    在您的情况下,需要显式地传递 record_object 到 fields_for

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

    也为了发送多个值 img news_params 至以下

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