Mass Assignment in Rails 5

Steps

Step 1

The new user registration page in app/views/users/new.html.erb has full name and password fields.

<%= form_for(@user) do |f| %>
  <div class="field">
    <%= f.label :full_name %>
    <%= f.text_field :full_name %>
  </div>
  <div class="field">
    <%= f.label :password %>
    <%= f.password_field :password %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

Step 2

If you use params[:user] when creating the user record like this:

def create
  User.create(params[:user])

  redirect_to users_path
end

You will get the error:

ActiveModel::ForbiddenAttributesError

Step 3

Add allowed_params method to users controller.

def allowed_params
  params.require(:user).permit(:full_name, :password)
end  

This method only allows the full_name and password fields in the user model. Use this method in the users controller.

def create
  User.create(allowed_params)

  redirect_to users_path
end

We will now be able to register a new user. Note: The attr_protected was deprecated in Rails 2.3.8. Rails 4.0 has removed attr_accessible and attr_protected feature in favor of Strong Parameters.

Summary

In this article, you learned how to use strong parameters that protects the Rails 5 web apps from mass assignment problems.


Related Articles


Ace the Technical Interview

  • Easily find the gaps in your knowledge
  • Get customized lessons based on where you are
  • Take consistent action everyday
  • Builtin accountability to keep you on track
  • You will solve bigger problems over time
  • Get the job of your dreams

Take the 30 Day Coding Skills Challenge

Gain confidence to attend the interview

No spam ever. Unsubscribe anytime.