Skip to content Skip to sidebar Skip to footer

Ruby On Rails: Basic Parameterized Queries And Url Formation

I'm trying to learn how to query a rails database and return the results as JSON. In my example, I want to query the data using the parameters, city and state. So far, in my contro

Solution 1:

You don't have to pass everything by the route - the URL also support GET parameters - those are the parameters you usually see after the question mark in the URL. You can add those GET parameters without changing your routes: http://localhost:3000/bathrooms/state/IL.json?city=Chicago. Then your can access the city parameter via params[:city]. but in your case, I think it will be better to use http://localhost:3000/bathrooms/index.json?state=IL&city=Chicago. You'll also need to change your routing to

match '/bathrooms/index',
    :controller=>:bathrooms,
    :action=>:index

and put the code in the index method of BathroomsController. You access the parameters the same - but the concept is different - you don't enter a state and look for bathrooms by city, you just look for bathrooms by state and city.

Anyways, you don't want to write the URL by hand - you want to a Rails helper or an HTML form generate it:

link_to "bathroom in Chicago, IL",:controller=>:bathrooms,:action=>:index,:state=>'IL',:city=>'Chicago'

If you want to use a form(to let the users choose their own state and city), you need to set it's method to GET:

form_tag {:controller=>:bathrooms,:action=>:index},:method=>:getdo

and put state and city as fields.

It's also worth noting that while you can use SQL's AND to perform a search by multiple fields, you can also chain where methods: Bathroom.where(:state=>params[:state]).where(:city=>params[:city]).

Solution 2:

You can put any arbitrary parameters in your querystring.

For example:

http://localhost:3000/bathrooms/state/CA.json?city=Chicago

your query looks like this:

@bathrooms = Bathroom.where("state = ? and city= ?" ,params[:state], params[:city])

Post a Comment for "Ruby On Rails: Basic Parameterized Queries And Url Formation"