Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - render custom xml

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.

like image 328
Exbi Avatar asked Sep 07 '11 11:09

Exbi


3 Answers

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.

like image 112
jaydel Avatar answered Oct 16 '22 10:10

jaydel


Try something like:

render :xml => chairs.select { |c| c.age== [:id]}
like image 44
lucapette Avatar answered Oct 16 '22 08:10

lucapette


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.

like image 1
Exbi Avatar answered Oct 16 '22 09:10

Exbi