Showing posts with label xml. Show all posts
Showing posts with label xml. Show all posts

Ok so what i'm trying to do is generate xml using the rails xml builder.

say you have a house and that house has several people living in it. I would have a relationship that looks like this:


class Person < ActiveRecord::Base
belongs_to :house 

end

class House < ActiveRecord::Base
has_may :people

end


Getting rails to build out some xml for the has_many relationship is pretty straight forward. for example:


xml.home do
xml.square_feet home.square_feet
home.people.each do |person|
xml.person do
xml.name person.name
xml.age person.name
end
end
end



which should output this xml

<home>
<square_feet>...</square_feet>
<person>
<name>...</name>
<age>...</age>
</person>
</home>


But in the case where you want to build out xml data for a belongs_to relationship i'm at a loss. I would have thought it would be even easier but that doesn't seem to be the case. Here is how I thought it would work.


xml.person do
xml.name person.name
xml.age person.age
xml.home do
xml.square_feet person.home.square_feet
end
end


which should output this xml

<person>
<name>...</name>
<age>...</age>
<home>
<square_feet>...</square_feet>
</home>
</person>


However for some reason person.home.square_feet does not work in the xml builder despite the fact that it works in the console.

I invite anyone with suggestions on how to make this work to comment or post links otherwise I will hopefully be posting a follow up article on how I eventually figured it out.

Resolved Post