【发布时间】:2010-04-28 22:33:13
【问题描述】:
我有一些我正在尝试使用关联的 ARes 模型(见下文)(这似乎完全没有记录,也许不可能,但我想我会试一试)
所以在我的服务端,我的 ActiveRecord 对象将呈现类似
render :xml => @group.to_xml(:include => :customers)
(见下方生成的 xml)
模型组和客户是HABTM
在我的 ARes 方面,我希望它可以看到 <customers> xml 属性并自动填充该 Group 对象的 .customers 属性,但不支持 has_many 等方法(至少就目前而言我知道)
所以我想知道 ARes 如何在 XML 上反射来设置对象的属性。例如,在 AR 中,我可以创建一个 def customers=(customer_array) 并自己设置它,但这似乎在 ARes 中不起作用。
我为“关联”找到的一个建议是要有一个方法
def customers
Customer.find(:all, :conditions => {:group_id => self.id})
end
但这样做的缺点是它会进行第二次服务调用来查找这些客户......不酷
我希望我的 ActiveResource 模型在 XML 中看到客户属性并自动填充我的模型。有人有这方面的经验吗?
# My Services
class Customer < ActiveRecord::Base
has_and_belongs_to_many :groups
end
class Group < ActiveRecord::Base
has_and_belongs_to_many :customer
end
# My ActiveResource accessors
class Customer < ActiveResource::Base; end
class Group < ActiveResource::Base; end
# XML from /groups/:id?customers=true
<group>
<domain>some.domain.com</domain>
<id type="integer">266</id>
<name>Some Name</name>
<customers type="array">
<customer>
<active type="boolean">true</active>
<id type="integer">1</id>
<name>Some Name</name>
</customer>
<customer>
<active type="boolean" nil="true"></active>
<id type="integer">306</id>
<name>Some Other Name</name>
</customer>
</customers>
</group>
【问题讨论】:
标签: ruby-on-rails associations activeresource