Mass Assignment in Rails 5
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 %>
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:
allowed_params method to users controller.
def allowed_params params.require(:user).permit(:full_name, :password) end
This method only allows the
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_protected feature in favor of Strong Parameters.
In this article, you learned how to use strong parameters that protects the Rails 5 web apps from mass assignment problems.
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