1

I'm using CarrierWave and to be able to remove a picture, I need to permit parameter which isn't a part of user:

params.require(:user).permit(:first_name, :last_name, :description, :picture, :remove_picture)

It gives me errors, but changing it to:

params.permit(:first_name, :last_name, :description, :picture, :remove_picture)

as suggested in one of topics on forum, gives errors too - "unpermitted parameters commit, id" etc. How can I require user and in the same time - permit remove_picture?

1 Answer 1

2

You should nest the remove_picture attribute under user like in the example in the readme:

<%= form_for @user, html: { multipart: true } do |f| %>
  <p>
    <label>My Avatar</label>
    <%= image_tag(@user.avatar_url) if @user.avatar? %>
    <%= f.file_field :avatar %>
  </p>

  <p>
    <label>
      <%= f.check_box :remove_avatar %>
      Remove avatar
    </label>
  </p>
<% end %>

That would let you do

params.require(:user)
      .permit(:first_name, :last_name, :description, :picture, :remove_picture)

The Rails mass assignment protection is basically just hash slicing:

  • .require pulls a single key from the hash and raises an error if its not there.
  • .permit returns the keys which are allowed and marks the hash as safe for mass assignment.

Its made to handle a hash nested under a single param key or at the root. While you can go crazy merging two hashes:

p = params.require(:user)
          .permit(:first_name, :last_name, :description, :picture)
p.merge!(params.permit(:remove_picture))

You are just creating problems for yourself.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for long answer, but I realized my problem is different. My image upload works fine, but when I click on "add avatar" without selecting file to be attached, I get "param is missing or the value is empty: user". Only parameters sent are utf8, method, authenticity_token, commit, id (but id without 'user' key). I set redirection in my controller, but it works only when 'user' is not required. I must find a way to not require user, but requiring him in the same time...
You can use params.fetch(:user, {}).permit(:a,:b,:c). But you should just look at the examples in the readme and nest the inputs properly. This is very likely an XY problem where your form is messed up but you are overly concentrated on using strong params to finagle around the problem. The end result is a inconsistent API. If you can't get it work add your form and controller to the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.