Search code examples
ruby-on-railsactiverecordstrong-parameters

Rails 4 - Unpermitted parameters for nested param despite whitelisting


I have two models user_item and user_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

I have a form where the user should submit a new user_item. The only field in the form is for pictures where the user can upload multiple pictures. On success, a single new user_item is created along with a new user_item_image for each picture that is uploaded.

form

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

When I submit the form I get Unpermitted parameter: user_item_images in the console and I can't figure out why.


Solution

  • Change this:

        <%= ..., name: "user_item_images[picture][]", ... %>
    

    to this:

        <%= ..., name: "user_item_images_attributes[picture][]", ... %>