Could anyone give any examples of how to use FOR and IF loops in a rails controller?
Here is some 'pseudo code' (using the term very loosely) which will hopefully illustrate what I want to do -
For the sake of this example, I am using a table called 'chairs' and I want to query the 'age' column to show all chairs that are (eg) 2 years old. [:id] is a numeric variable that I'm passing into it. in my working project I have already set up the routes and am able to render basic :all xml to the URL, but I need it to display specific records, as follows...
For each chair in chairs
if chair.age = [:id]
render records to xml
end
end
Would appreciate any help.
Edit - i understand how FOR and IF loops work, just need some examples of how to achieve the above in the rails controller.
In your chairs model:
class Chair < ActiveRecord::Base
:scope :years_old, lambda { |time_ago| { :conditions => ['age == ?', time_ago] }
end
Then you can do:
render :xml => Chairs.years_old(2)
I'm foggy on the exact syntax of render, but creating the scope allows you to make your controller code more readable and not have to do the looping/conditionals there. Just name your scope something clear and easy to understand...
This all assumes that you want to get all chairs that are age == 2, not just a subset of some other search. If this assumption is wrong, then Lucapette's answer is better.
Try something like:
render :xml => chairs.select { |c| c.age== [:id]}
Thanks for the suggestions, helped alot. Here is what I did to get it working, maybe someone else will find it useful (I don't know if this is the best way, but it works)
First set up the route in routes.rb - match '/chair/age/:id', :controller=> 'chairs', :action=> 'displaychairs'
Then in chairs controller -
def displaychairs
chid=params[:id]
@chairs = Chair.find(:all, :conditions => [ "age = ?",chid])
respond_to do |format|
format.xml { render :xml => @chairs }
end
end
Then I could use /chair/age/*.xml in my app (where * is the variable (age of chair) that was passed in.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With