在 ActiveRecord 下的 to_xml 为您提供了许多将 model 载入 xml 的选择。您所拥有的 :only (只有) 和 :except (除了) 实参可以使您 向里/向外 过滤某些属性。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
user = User.find(1) user.to_xml(:except => [:id, :created_at]) # 这里显示除了 id, created_at 之外所有的值。 #=> # <user> # <name>Ryan</name> # <email>ryan@spamme.com</email> # </user> user.to_xml(:only => [:email]) # 这里只选择显示电子邮件。 #=> # <user> # <email>ryan@spamme.com</email> # </user> |
(如果想在加载过程中引用method输出的结果,可以使用 :method 选项)1
您还可以将属于第一级别的联系包括在 :include 中:
1 2 3 4 5 6 7 8 9 |
user.to_xml(:except => [:id, :created_at], :include => :posts) #=> # <user> # <name>Ryan</name> # <email>ryan@spamme.com</email> # <posts> # <post><title>What's New in Edge Rails</title></post> # </posts> # </user> |
请注意在 xml builder 代码中包含了标准建立的 XML 句子 – 不过您现在可以同 custom element 以及其他结构配合使用。算是另一个为方便您加载到xml的小工具。
注解
1 to_xml 里,向对象添加method的时候使用 :methods firm.to_xml :methods => [ :calculated_earnings, :real_earnings ]
1 2 3 4 5 |
<firm>
# ... 上面显示例行属性
<calculated-earnings>100000000000000000</calculated-earnings>
<real-earnings>5</real-earnings>
</firm> |
原文作者是 Ryan Daigle, 请访问他的博客
本片译文的原文地址:http://ryandaigle.com/articles/2007/4/13/what-s-new-in-edge-rails-a-more-flexible-to_xml



