Let’s talk about Rails parameters!
Why are they useful?
Users can send data to your web application in three different ways.
These three ways are:
- Using a query parameter (
"example.com/?q=bacon"
) - Submitting a form (
"/users/sign_in"
) - Within the URL itself (
"/books/1"
)
How do you access this data from Rails?
With params
.
Inside your controller action’s you can call params
to access form & URL query data.
What is params
, exactly?
It’s a method that returns an ActionController::Parameters
object, in practice it behaves a lot like a hash.
Now.
Let’s say that you want to read one value from this params
hash.
Here’s how:
params[:id]
You get the value if it exists.
Or nil
if it doesn’t.
Few things to know:
- If a field is left blank you’ll get an empty string
- All values inside
params
are strings. Even if they’ve been submitted as integers
Let’s look a little deeper into Rails params because if you don’t understand them well they can be a source of confusion & strange problems!
Rails Conventions: Form Fields & Params
How do form fields & URL parameters map to params
keys?
I have an example for you.
Here:
This is a simple search form that will send a POST request to /search
.
As a result, you’ll get this params
object:
{ "q"=>"", "controller"=>"books", "action"=>"search" }
What is this “q”?
It’s the name attribute of the input field in the HTML form.
The name can be anything you want.
If you create your form using the form_for
helper method, the names are auto-generated for you & they follow a specific pattern.
Here’s an example:
# form_for(@book) with a few fields generates something like this
This book[title]
format in the field names will generate a params
hash where the values will be nested.
Let me explain with an example:
{ "book"=> { "title"=>"", "author"=>"", "cover"=>"", "language"=>"English" } }
User submits a blank form & this is what you get.
From your controller…
You access the data like this:
params[:book][:language] # "English" params[:book][:author] # ""
Remember that this behaves like a hash, but unlike a regular hash, it will accept both symbols & strings as equivalent keys.
Meaning that params["book"]
& params[:book]
are the same.
Enabling Your Routes to Accept Parameters
Besides query parameters, you can also enable REST-style parameters.
In Rails, we call this is a “dynamic segment”.
Let’s see an example.
If you have a route like:
get 'books/:id', to: 'books#show'
Or:
resources :books
You’ll be able to use URLs like this:
/books/1
Then you can access this 1
, which is the id
in books/:id
.
With params
.
Like this:
params[:id]
This will help you find the specific resource the user is looking for.
Book.find(params[:id])
Understanding Strong Params
Next:
If you try to save an object to your database, but it doesn’t seem to work.
Look at your rails server log.
You may see this:
Unpermitted parameter: :language
What does this mean?
Rails introduced the “strong parameters” system, back in Rails 4 as a security feature.
It forces you to whitelist the attributes that can be saved.
This prevents an issue known as “mass assignment”, which allows malicious users to set admin = true
, or set other fields that normally they wouldn’t have access to.
You can whitelist fields like this:
def book_params params.require(:book).permit(:title, :author, :cover, :language) end
How does this work?
- The
require
method will look forparams[:book]
& raise an error if it’s not there. - The
permit
method is a list of allowed (but optional) attributes.
As a result, you get back a new params
hash with these attributes, but now they’re clear to be saved to the database.
Example:
Book.create(book_params)
Notice that a regular Ruby hash will bypass this security system.
Example:
Book.create(title: "", author: "", cover: "")
This should be ok if the attribute names (like author
) are hardcoded.
Summary
You’ve learned about Rails parameters, how they work & how to use them correctly in your Rails projects!
Now it’s your turn to practice, take notes, review 🙂
Thanks for reading.
Nice one, now I know.
Great, keep learning! 🙂
Another great post Jesus. Keep it up.
Thank you! 🙂
Thanks very much Jesus! Params are something I’ve been finding quite tough to grasp. I’m very grateful for this article. I think I’ve understood it much more than I used to. U explain so well. Not just here but in all ur articles. Will try to practice like u’re advising. Thanks once again
Thanks for reading Christian! I’m glad you found this article helpful 🙂
nice point you have taken