我有一些ARes模型(见下文),我正在尝试使用关联(这似乎完全没有文档,而且可能不可能,但我想尝试一下)
因此,在我的服务端,我的ActiveRecord对象将呈现如下
render :xml => @group.to_xml(:include => :customers)(见下面生成的xml )
模型组和客户是HABTM
在我的ARes方面,我希望它能够看到<customers>属性并自动填充该Group的.customers属性,但是has_many等方法不受支持(至少据我所知)
因此,我想知道ARes是如何在XML上反射来设置对象的属性的。例如,在AR中,我可以创建一个def customers=(customer_array)并自己设置它,但这在ARes中似乎行不通。
我为“联想”找到了一个建议,那就是有一个方法。
def customers
Customer.find(:all, :conditions => {:group_id => self.id})
end但这有一个缺点,那就是它打第二个服务电话去查那些客户.不酷
--我希望我的ActiveResource模型能看到客户在ActiveResource中的属性,并自动填充我的模型。有人对此有任何经验吗??
# 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>发布于 2010-04-28 23:10:16
ActiveResource不支持关联。但它并不妨碍您将复杂数据设置/从ActiveResource对象获取。以下是我将如何实现它:
服务器端模型
class Customer < ActiveRecord::Base
has_and_belongs_to_many :groups
accepts_nested_attributes_for :groups
end
class Group < ActiveRecord::Base
has_and_belongs_to_many :customers
accepts_nested_attributes_for :customers
end服务器端GroupsController
def show
@group = Group.find(params[:id])
respond_to do |format|
format.xml { render :xml => @group.to_xml(:include => :customers) }
end
end客户端模型
class Customer < ActiveResource::Base
end
class Group < ActiveResource::Base
end客户端GroupsController
def edit
@group = Group.find(params[:id])
end
def update
@group = Group.find(params[:id])
if @group.load(params[:group]).save
else
end
end客户端视图:从组对象访问客户
# access customers using attributes method.
@group.customers.each do |customer|
# access customer fields.
end客户端:将客户设置为组对象
group.attributes['customers'] ||= [] # Initialize customer array.
group.customers << Customer.buildhttps://stackoverflow.com/questions/2733571
复制相似问题