Contact iFingers

Finger Tips - a fistful of handy web notes

Saturday, July 28, 2007

Rails params

Working with PHP, I developed a fondness for using the URL as a means of querying my MySQL database. Often using the $_POST and $_GET commands to retrieve the names and values from the URL's query string. With Ruby on Rails we use the params method.

params

I have just had the pleasure of watching the Rails from Scratch Pt1 movie from PeepCode. They have a good section in the movie describing params, and how we can use it to create a hash to pass data to the view.

Rails by convention uses the following path in it's URL path:
/:controller/:action/:id

This makes it very easy to create links either dynamically or with static queries, and we have the params method which we can use to grab stuff from the URL query string. Here are some examples which can be pasted into a :controller and then the results will be magically available in your view.

#place this in your controller which sets the id from the URL into the @message_from_params instance variable @message_from_params = params[:id]

Then place the @message_from_params instance variable in your view:

<%= @message_from_params %>

So with a url of /machines/index/1, the message from params would be: 1.
Yet, Rails is clever enough to accept strings as well. So, /machines/index/1-Robots, we would get 1-Robots.
Get the idea? If not check out the PeepCode!

Grabbing Query Strings

So if we have a query string like this: /machines/index/robots?name=R2D2. We could then create an instance variable in our Machines Controller like this:

@name = params[:name]

Then place something like this in our view: Name: <%= @name %> and your web browser will return: "Name: R2D2".

Use params, NOT @params

According to the people that should know, it is important to avoid calling @params, as this is now deprecated. Learn More.

Labels: ,

0 Comments:

Post a Comment

<< Home