views:

23

answers:

1

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.

+1  A: 

You can use the :methods argument to to_xml for this serialization. You can either call it directly in your action (i.e. 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.

x1a4