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&param2=somevalue2

the rails server receives request client wants view get /posts/1/?param1=somevalue1&param2=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 set params[:id] value of :id. answer question params[: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 on params[:user_id] , params[:id] respectively.

  • in addition url params :id, rails injects values params[:controller] , params[:action] automatically routes. example above, get '/posts/:id', to: 'posts#show', set params[:controller] 'posts', , params[:action] 'show'.

  • params values comes other sources "query string" described mayur, , comes body of request, when submit form (the form values set within body part of request) , when have json requests, of these automatically parsed rails convenience, access params , values need them.


Comments

Popular posts from this blog

html - How to set bootstrap input responsive width? -

javascript - Highchart x and y axes data from json -

javascript - Get js console.log as python variable in QWebView pyqt -