ruby on rails - How does the params method work? -
i have been trying figure out how params method works , i'm bit stuck on process.
for example, if user clicks on blog post in index page, guess link_to method calls post controller , show action along block @post = post.find(params[:id])
, goes database find post , view displays it.
so missing link seems when post id passed params method?
because others explained params
, i'm going answer directly question of yours:
when post id passed params method
i think it's best explained example; see below:
say clicked link: /posts/1/?param1=somevalue1¶m2=somevalue2
the rails server receives request client wants view get /posts/1/?param1=somevalue1¶m2=somevalue2
address.
to determine how rails server respond, server first go routes.rb
, find matching controller-action handle request:
# let's routes.rb contain line # resources :posts # resources :posts above contains many routes. 1 of them below # sake of example, commented above code, , want focus on route: '/posts/:id', to: 'posts#show'
from above notice there
:id
, rails automatically setparams[:id]
value of:id
. answer questionparams[:id]
comes from.it doesn't have
:id
; can name whatever want. can have multiple url params (just example):get /users/:user_id/posts/:id
automatically set value onparams[:user_id]
,params[:id]
respectively.in addition url params
:id
, rails injects valuesparams[:controller]
,params[:action]
automatically routes. example above,get '/posts/:id', to: 'posts#show'
, setparams[:controller]
'posts'
, ,params[:action]
'show'
.params
values comes other sources "query string" described mayur, , comesbody
of request, when submit form (the form values set withinbody
part of request) , when have json requests, of these automatically parsed rails convenience, accessparams
, values need them.
Comments
Post a Comment