我有一些我正在尝试使用关联的 ARes 模型(见下文)(这似乎完全没有记录,也许不可能,但我想我会试一试)
所以在我的服务端,我的 ActiveRecord 对象将呈现类似
render :xml => @group.to_xml(:include => :customers)
(请参阅下面生成的 xml)
模型组和客户是HABTM
在我的 ARes 方面,我希望它可以看到<customers>
xml 属性并自动填充该.customers
Group 对象的属性,但不支持 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>