2009-08-26 55 views
1

我的自定義訪問方法的工作如下面的例子:如何使用to_xml呈現自定義字段?

class Forest < ActiveRecord : Base 
    has_many :trees 

    def total_water_usage 
    # summarize each tree's water_usage in this forest. 
    # return as string 
    end 

end 

class Tree < ActiveRecord : Base 
    belongs_to :forest 

end 

也就是說,我需要你的2個問題求助:

  1. 如何訪問每棵樹只是一個實例森林類。 (下面的例子一樣,總用水量不應該總結另一個森林的樹)

    asiaForest = Forest.find_by_name('asia') 
    asiaForest.total_water_usage 
    
  2. 我怎麼能強迫該方法通過to_xml方法呈現?例如,我想結果應該與此類似:

    asiaForest.to_xml 
    <asiaForest> 
        ... 
        <total_water_usage>239000</total_water_usage> 
        ... 
    </asiaForest> 
    

你能幫我做到這一點?

+0

爲to_xml的文檔:http://api.rubyonrails.org/classes/ActiveRecord/XmlSerialization.html – Swanand 2009-08-26 11:56:51

回答

7

records.to_xml(:methods => :total_water_usage)

+0

+1。簡單明瞭。 – Swanand 2009-08-26 11:55:00

0

的答案如下:

class Forest < ActiveRecord::Base 
    has_many :trees 

    def total_water_usage 
    trees.sum(:water_usage) 
    end 

    def to_xml 
    attributes["total_water_usage"] = total_water_usage 
    attributes.to_xml({:root => self.class.element_name}) 
    end 
end 

class Tree < ActiveRecord::Base 
    belongs_to :forest 

    def water_usage 
    # place your water usage calculation for a tree here 
    end 
end 

說明: 部分的問題1中total_water_usage它將調用water_usage每個樹和概括回答。我們不得不重寫to_xml方法來包含total_water_usage鍵。採用最初的to_xml方法。

1

要在全局模型範圍內實施,您可以將其添加到模型文件中。

alias_method :ar_to_xml, :to_xml 

    def time_zone_offset 
     get_my_time_zone_offset_or_something 
    end 

    def to_xml(options = {}, &block) 
    default_options = { :methods => [ :time_zone_offset ]} 
    self.ar_to_xml(options.merge(default_options), &block) 
    end