How to Use Rails Params

09/22/2021

Contents

In this article, you will learn how to use Rails Params.

Using Rails Params

Rails Params is a Ruby module that provides access to HTTP parameters such as query string parameters and form data submitted in an HTTP request. Here are some common use cases for working with Rails Params:

Accessing Query String Parameters

To access query string parameters in a Rails controller, you can use the params hash. For example, if you have a URL like this: /articles?category=ruby, you can access the category parameter like this:

category = params[:category]

Accessing Form Data

If you are working with a form that has been submitted via an HTTP POST request, you can access the form data using the same params hash. For example, if you have a form with a text field named “name”, you can access the submitted value like this:

name = params[:name]

Strong Parameters

Rails also provides a mechanism for whitelisting parameters to prevent mass assignment vulnerabilities. This is called “Strong Parameters”. To use strong parameters, you need to define a whitelist of allowed parameters for a given model. Here is an example:

class UsersController < ApplicationController
  def create
    @user = User.new(user_params)
    if @user.save
      # ...
    else
      # ...
    end
  end

  private

  def user_params
    params.require(:user).permit(:name, :email, :password)
  end
end

In the example above, the user_params method defines a whitelist of allowed parameters for the User model. The require method ensures that the :user parameter is present in the request, and the permit method allows only the specified parameters to be assigned.

Nested Parameters

If you are working with nested parameters, you can use the permit method to whitelist them as well. Here is an example:

def book_params
  params.require(:book).permit(:title, :author, :publisher, { pages: [] })
end

In the example above, the book_params method whitelists the :title, :author, and :publisher parameters, as well as any nested :pages parameters that may be submitted as an array.