Thursday 19 May 2011

Using virtual attributes in ruby model.to_xml

If you have virtual attributes that you want to include in your to_xml call then you can override the to_xml on the model and pass the virtual attributes as methods. For example

class ModelName < ActiveRecord::Base
has_one :model_name_2

# real attributes a, b
attr_accessor :c, :d
delegate e, :to => :model_name_2
end

Now an instance (mn) of type ModelName calling to_xml will output

mn.to_xml

115true

Now to override the to_xml to include attributes c, d and e.

class ModelName < ActiveRecord::Base
has_one :model_name_2

class ModelName < ActiveRecord::Base
has_one :model_name_2
# real attributes a, b
attr_accessor :c, :d
delegate e, :to => :model_name_2

def to_xml
super(:methods => [:c, :d, e])
end
end

Now when to_xml is called on the model c, d and e will also be included.

mn.to_xml

115trueAnExamplefrom another model

No comments:

Post a Comment