我有一些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模型能够看到customer属性在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>
最佳答案
ActiveResource不支持关联。但这并不能阻止您向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
客户 View :从组对象访问客户
# access customers using attributes method.
@group.customers.each do |customer|
# access customer fields.
end
客户端:将客户设置为组对象
group.attributes['customers'] ||= [] # Initialize customer array.
group.customers << Customer.build
关于ruby-on-rails - Rails ActiveResource协会,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2733571/