Rails 4 - 嵌套参数的未允许参数,尽管白名单

时间:2016-02-25 00:44:22

标签: ruby-on-rails activerecord strong-parameters

我有两个模型user_itemuser_item_images

schema.rb

  create_table "user_item_images", force: :cascade do |t|
    t.integer  "user_item_id"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "picture"
  end

  create_table "user_items", force: :cascade do |t|
    t.integer  "user_id"
    t.integer  "item_id"
    t.integer  "status",          default: 0
    t.boolean  "hide_banner",     default: false
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "picture"
    t.string   "declined_reason"
  end

我有一个表单,用户应该提交新的user_item。表单中唯一的字段是用户可以上传多张图片的图片。成功时,会为每张上传的图片创建一个新的user_item以及一个新的user_item_image

形式

    <%= simple_form_for :user_item, url: user_items_path, html: {multipart: true} do |user_item_builder| %>
      <%= user_item_builder.input :item_id, as: :hidden, input_html: { value: "#{@item.id}" } %>
      <%= user_item_builder.simple_fields_for :user_item_images do |user_item_images_builder| %>
        <%= user_item_images_builder.input :picture, as: :file, label: false, name: "user_item_images[picture][]", input_html: { multiple: true } %>
      <% end %>
    <% end %>

user_item_controller.rb

  def create
    @user_item = current_user.user_items.new(user_item_params)
    raise 'foo'
    if @user_item.save
      params[:user_item][:user_item_images]['picture'].each do |a|
        @user_item_image = @user_item.user_item_images.create!(:picture => a)
      end
      # Sends email to user when item request is created.
      itemMailer.user_item_submission_email(current_user, @user_item.item).deliver_later

      flash[:notice] = "Thank you for your item request!"
    else
      @user_item.errors.full_messages.each do |message|
        flash[:alert] = message
      end
    end

    redirect_to item_path(@user_item.item)
  end

  private 

  def user_item_params
    params.require(:user_item).permit(:item_id, user_item_images_attributes: [:user_item_id, :picture])
  end

user_item.rb

  belongs_to :user
  has_many :user_item_images
  mount_uploader :picture, PictureUploader

  accepts_nested_attributes_for :user_item_images

user_item_image.rb

  mount_uploader :picture, PictureUploader
  belongs_to :user_item

当我提交表单时,我在控制台中得到Unpermitted parameter: user_item_images,我无法找出原因。

1 个答案:

答案 0 :(得分:1)

改变这个:

col2

到此:

col3