Robert Robert - 3 years ago 38
Ruby Question

How does the params method work?

I have been trying to figure out how the params method works and I'm a bit stuck on the process.

For example, if a user clicks on a certain blog post in the index page, I guess that the link_to method calls the Post controller and the show action along with its block

@post = Post.find(params[:id])
and then goes to the database to find the post and the view displays it.

So my missing link seems to be when is the post id passed into the params method?

Answer Source

Because the others already explained about params, I'm just going to answer directly a question of yours:

when is the post id passed into the params method

I think it's best explained with an example; see below:

say that you clicked a link: /posts/1/?param1=somevalue1&param2=somevalue2

The Rails server receives this request that a client wants to view this GET /posts/1/?param1=somevalue1&param2=somevalue2 address.

To determine how the Rails server will respond, the server will first go to your routes.rb and find the matching controller-action that will handle this request:

# let's say your routes.rb contain this line
# resources :posts

# resources :posts above actually contains MANY routes. One of them is below
# For sake of example, I commented above code, and I only want you to focus on this route:
get '/posts/:id', to: 'posts#show'
  • From above notice that there is this :id, Rails will automatically set params[:id] to the value of this :id. This is the answer to your question where params[:id] comes from.

  • It doesn't have to be :id; you can name it whatever you want. You can even have multiple URL params like so (just an example):

    get /users/:user_id/posts/:id which will automatically set the value on params[:user_id] and params[:id] respectively.

  • In addition to this URL params like :id, Rails also injects values to params[:controller] and params[:action] automatically from the routes. Say from the example above, get '/posts/:id', to: 'posts#show', this will set params[:controller] to 'posts', and params[:action] to 'show'.

  • params values also comes from other sources like the "Query string" as described by Mayur, and also comes from the body of the request, like when you submit a form (the form values are set within the body part of the request) and like when you have JSON requests, which all of these are automatically parsed by Rails for your convenience, so you could just simply access params and get the values as you need them.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download