如何使用to_xml呈现自定义字段?

Tee*_*sej 1 activerecord ruby-on-rails

我正在开发一个自定义访问器方法,如下例所示:

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
Run Code Online (Sandbox Code Playgroud)

也就是说,我需要你的2个问题的帮助:

  1. 如何仅为Forest类的实例访问每个树.(如下图所示,总用水量不应总结另一棵森林的树木)

    asiaForest = Forest.find_by_name( 'asia' )
    asiaForest.total_water_usage
    
    Run Code Online (Sandbox Code Playgroud)
  2. 如何通过to_xml方法强制使用此方法?例如,我认为结果应该类似于:

    asiaForest.to_xml
    <asiaForest>
       ...
       <total_water_usage>239000</total_water_usage>   
       ...
    </asiaForest>
    
    Run Code Online (Sandbox Code Playgroud)

你能帮帮我吗?

Rya*_*igg 7

records.to_xml(:methods => :total_water_usage)