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])
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:
The Rails server receives this request that a client wants to view this
GET /posts/1/?param1=somevalue1¶m2=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
In addition to this URL params like
:id, Rails also injects values to
params[:action] automatically from the routes. Say from the example above,
get '/posts/:id', to: 'posts#show', this will set
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.