In this tutorial, we aim to understand how to use strong parameters feature in Rails framework to enhance the security of our web application.
After completing this tutorial, you will be able to:
- Understand the importance of strong parameters in Rails
- Implement strong parameters in your Rails application
- Maintain a more secure application by filtering out unwanted parameters
Strong Parameters is a feature in Rails that prevents assigning request parameters to models directly. It provides an interface to protect assignment of attributes from end-user manipulation.
In Rails, we have a concept of mass assignment. Mass assignment allows you to update multiple attributes at once in your models. This is good, but it can be exploited to update fields you don't want to be updated. That's where strong parameters come in. They allow us to specify which parameters should be permitted and which should be blocked.
It's always a good practice to use strong parameters in your controller to prevent any unwanted manipulation of model data.
class UsersController < ApplicationController
def create
@user = User.new(user_params)
if @user.save
redirect_to @user
else
render 'new'
end
end
private
def user_params
params.require(:user).permit(:name, :email, :password, :password_confirmation)
end
end
In the code above:
- params.require(:user)
ensures that the :user
parameter is present
- .permit(:name, :email, :password, :password_confirmation)
lists the parameters that are allowed. Any other parameters will be filtered out.
def user_params
params.require(:user).permit(:name, :email, :password, :password_confirmation, addresses_attributes: [:id, :street, :city, :state, :zip])
end
In this example, we are permitting nested attributes for addresses
.
In this tutorial, we have learned about strong parameters in Rails and how they help maintain a secure application. We also saw how to implement them in our application. The next step would be to understand more about Rails security and apply other techniques to make your application more secure.
Post
model with title
and content
as attributes.Product
model, which has nested attributes for a Category
model.Post
model:class PostsController < ApplicationController
def create
@post = Post.new(post_params)
if @post.save
redirect_to @post
else
render 'new'
end
end
private
def post_params
params.require(:post).permit(:title, :content)
end
end
Product
model with nested Category
:def product_params
params.require(:product).permit(:name, :price, category_attributes: [:id, :name])
end
Keep practicing and try to implement strong parameters in different scenarios to understand more about it. Happy Coding!