Tutorial :Customizing Rails XML rendering to include extra properties



Question:

Let's say I have a model like this:

create_table :ninjas do |t|    t.string name  end  

And the Ninja class with an extra property:

class Ninja < ActiveRecord::Base    def honorific      "#{name}san"    end  end  

And in my controller I just want to render it to XML:

def show    render :xml => Ninja.find(params[:id])  end  

The honorific part isn't rendered. That makes sense, since it's just a method, but is there a way of tricking it?

I'm totally up for answers to the effect of, "You're doing this totally wrong." I'll just add that I really do want to calculate the honorific on the fly, and not, like, store it in the database or something.


Solution:1

You can use the :methods argument to to_xml for this serialization. You can either call it directly in your action...

render xml: Ninja.find(params[:id]).to_xml(methods: :honorific)  

...or redefine to_xml in your Ninja class to always include it.

Take a look at the docs for more info.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »