# Generating XML in a model

**URL:** <https://www.ruby-forum.com/t/generating-xml-in-a-model/148495>\
**Category:** Rails\
**Created:** [September 13, 2008, 5:12pm UTC](https://www.ruby-forum.com/t/generating-xml-in-a-model/148495 "2008-09-13T17:12:28Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![adam](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/4af34b/32.png) [@adam](https://www.ruby-forum.com/u/adam)\
**Post date:** [September 13, 2008, 5:12pm UTC](https://www.ruby-forum.com/t/generating-xml-in-a-model/148495/1 "2008-09-13T17:12:28Z")

</div>

Hi all,

I have an application that produces an RSS feed of blog posts. To do  
this, I have a file rss.rxml that contains code like this:

@blogs.each do |blog|  
xml.item do  
xml.title blog.subject  
xml.link blogs\_path  
xml.description blog.body  
xml.guid blogs\_path  
xml.pubDate blog.created\_at  
end  
end

I want to move this code into a to\_rss method on my Blog model, so  
that I can simply write:

@blogs.each do |blog|  
blog.to\_rss  
end

The idea here is that it should be really easy to add other items to  
my rss feed, like photos or events - my view file can then generate  
the feed for a collection of arbitrary objects, as long as the models  
all have to\_rss methods.

My question is, what do I need to include in the model in order to use  
the xml builder? I want to write in blog.rb

def to\_rss  
xml.item do  
xml.title self.subject  
xml.link blogs\_path  
xml.description self.body  
xml.guid blogs\_path  
xml.pubDate self.created\_at  
end  
end

This raises an error like “undefined variable xml”. Does anyone know  
how to solve this?

Many thanks,  
Adam

---

<div class="post-metadata">

**Author:** ![adam](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/4af34b/32.png) [@adam](https://www.ruby-forum.com/u/adam)\
**Post date:** [September 13, 2008, 5:15pm UTC](https://www.ruby-forum.com/t/generating-xml-in-a-model/148495/2 "2008-09-13T17:15:24Z")

</div>

On 13 Sep 2008, at 16:11, Adam wrote:

> ```
> xml.guid blogs_path
> xml.pubDate self.created_at
> 
> ```
> 
> end  
> end

> This raises an error like “undefined variable xml”. Does anyone know  
> how to solve this?

In the context of an rxml view, an instance of Builder::XMLMarkup has  
already been created for you and assigned to the local variable xml.  
You just need to do the same. See also the examples at  
[http://builder.rubyforge.org/](http://builder.rubyforge.org/)

Fred

---

<div class="post-metadata">

**Author:** ![adam](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/4af34b/32.png) [@adam](https://www.ruby-forum.com/u/adam)\
**Post date:** [September 13, 2008, 5:20pm UTC](https://www.ruby-forum.com/t/generating-xml-in-a-model/148495/3 "2008-09-13T17:20:05Z")

</div>

Thanks Fred - I just solved the problem by passing the xml variable to  
the to\_rss method, and now I feel a bit silly for asking! 🙂
