Exbi
Exbi

Reputation: 970

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.

Upvotes: 5

Views: 1472

Answers (3)

Exbi
Exbi

Reputation: 970

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.

Upvotes: 1

user483040
user483040

Reputation:

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.

Upvotes: 3

lucapette
lucapette

Reputation: 20724

Try something like:

render :xml => chairs.select { |c| c.age== [:id]}

Upvotes: 1

Related Questions