Could anyone explain params
in Rails controller: where they come from, and what they are referencing?
def create
@vote = Vote.new(params[:vote])
item = params[:vote][:item_id]
uid = params[:vote][:user_id]
@extant = Vote.find(:last, :conditions => ["item_id = ? AND user_id = ?", item, uid])
last_vote_time = @extant.created_at unless @extant.blank?
curr_time = Time.now
end
I would like to be able to read this code line-by-line and understand what's going on.
As others have pointed out,
params
values can come from the query string of a GET request, or the form data of a POST request, but there's also a third place they can come from: The path of the URL.As you might know, Rails uses something called routes to direct requests to their corresponding controller actions. These routes may contain segments that are extracted from the URL and put into
params
. For example, if you have a route like this:Then a request to a URL like
http://example.com/products/42
will setparams[:id]
to42
.Basically, parameters are user specified data to rails application.
When you post a form, you do it generally with POST request as opposed to GET request. You can think normal rails requests as GET requests, when you browse the site, if it helps.
When you submit a form, the control is thrown back to the application. How do you get the values you have submitted to the form?
params
is how.About your code.
@vote = Vote.new params[:vote]
creates new Vote to database using data of params[:vote]. Given your form user submitted was named under name :vote, all data of it is in this :vote field of the hash.Next two lines are used to get item and uid user has submitted to the form.
finds newest, or last inserted, vote from database with conditions item_id = item and user_id = uid.
Next lines takes last vote time and current time.
The params come from the user's browser when they request the page. For an HTTP GET request, which is the most common, the params are encoded in the url. For example, if a user's browser requested
http://www.example.com/?foo=1&boo=octopus
then
params[:foo]
would be "1" andparams[:boo]
would be "octopus".In HTTP/HTML, the params are really just a series of key-value pairs where the key and the value are strings, but Ruby on Rails has a special syntax for making the params be a hash with hashes inside. For example, if the user's browser requested
http://www.example.com/?vote[item_id]=1&vote[user_id]=2
then
params[:vote]
would be a hash,params[:vote][:item_id]
would be "1" andparams[:vote][:user_id]
would be "2".The Ruby on Rails params are the equivalent of the $_REQUEST array in PHP.
On the Rails side,
params
is a method that returns anActionController::Parameters
object. See https://stackoverflow.com/a/44070358/5462485Params contains the following three groups of parameters:
match '/user/:id'
in routes.rb will set params[:id]params[:controller]
andparams[:action]
is always available and contains the current controller and action