开发者

Customizing Rails XML rendering to include extra properties

Let's say I have a model like this:

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

And t开发者_开发百科he 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜