How to Use the Rails require and permit

Contents
In this article, you will learn how to use the Rails require and permit method.
Using the Rails require and permit methods
The require and permit methods are used in Ruby on Rails to whitelist parameters passed in from user input, such as form submissions.
Here’s how you can use them:
In your controller, define a private method called resource_params that uses the params method to retrieve the parameters you want to permit.
class ResourcesController < ApplicationController
# ...
private
def resource_params
params.require(:resource).permit(:name, :description, :category_id)
end
end
In the example above, params.require(:resource) specifies that the :resource parameter is required, and permit(:name, :description, :category_id) allows only the :name, :description, and :category_id parameters to be passed in.
When you create or update a resource, use the resource_params method to retrieve the permitted parameters.
class ResourcesController < ApplicationController
# ...
def create
@resource = Resource.new(resource_params)
if @resource.save
redirect_to @resource
else
render 'new'
end
end
def update
if @resource.update(resource_params)
redirect_to @resource
else
render 'edit'
end
end
end
In the example above, Resource.new(resource_params) creates a new Resource instance with the permitted parameters, and @resource.update(resource_params) updates an existing Resource instance with the permitted parameters.
By using the require and permit methods, you can prevent unauthorized parameters from being passed in and potentially compromising your application's security.