Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I render a .builder template in ruby on rails?

I am really confused about how to utilize builder templates in ruby on rails. I have some simple controller code:

class ProductsController < ApplicationController

  def index
    @products = Product.all
    respond_to do |format|
      format.html # index.html.erb
      format.xml  # index.builder
    end
  end

end

but this does not seem to work. My index.builder file looks like this:

xm = Builder::XmlMarkup.new(:target=>$stdout, :indent=>2)
xm.instruct!          
  xm.index{
    @index.each do |i|
      xm.country(i.country.name)
      xm.value(i.value)
      xm.year(i.year)
    end
  }

but I keep getting a blank response. Looks like I am not understanding something fundamental here.

like image 238
user270524 Avatar asked Dec 30 '22 01:12

user270524


1 Answers

Rename index.builder to index.xml.builder and then the xml object is already available in index.builder, so you can tweak your builder file to look like this:

xml.instruct!
xml.posts do
  @products.each do |product|
    xml.product do
      xml.title product.title
      xml.body product.body
      xml.price product.price
    end
  end
end

More here: http://danengle.us/2009/05/generating-custom-xml-for-your-rails-app/

like image 108
Andrew Nesbitt Avatar answered Jan 09 '23 14:01

Andrew Nesbitt