我的自定義訪問方法的工作如下面的例子:如何使用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個問題求助:
如何訪問每棵樹只是一個實例森林類。 (下面的例子一樣,總用水量不應該總結另一個森林的樹)
asiaForest = Forest.find_by_name('asia') asiaForest.total_water_usage
我怎麼能強迫該方法通過to_xml方法呈現?例如,我想結果應該與此類似:
asiaForest.to_xml <asiaForest> ... <total_water_usage>239000</total_water_usage> ... </asiaForest>
你能幫我做到這一點?
爲to_xml的文檔:http://api.rubyonrails.org/classes/ActiveRecord/XmlSerialization.html – Swanand 2009-08-26 11:56:51