bra*_*rad 6 ruby-on-rails associations activeresource
我有一些ARes模型(见下文),我正在尝试使用关联(这似乎完全没有文档,也许不可能,但我想我会尝试一下)
所以在我的服务方面,我的ActiveRecord对象将呈现类似的东西
render :xml => @group.to_xml(:include => :customers)
Run Code Online (Sandbox Code Playgroud)
(参见下面生成的xml)
模型组和客户是HABTM
在我的ARes方面,我希望它可以看到<customers>xml属性并自动填充该.customersGroup对象的属性,但是不支持has_many等方法(至少据我所知)
所以我想知道ARes如何反映XML来设置对象的属性.例如,在AR中,我可以def customers=(customer_array)自己创建并设置它,但这似乎在ARes中不起作用.
我找到一个"关联"的建议就是有一个方法
def customers
Customer.find(:all, :conditions => {:group_id => self.id})
end
Run Code Online (Sandbox Code Playgroud)
但这有一个缺点,就是它会进行第二次服务电话来查找这些客户......并不酷
我希望我的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>
Run Code Online (Sandbox Code Playgroud)
Har*_*tty 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
Run Code Online (Sandbox Code Playgroud)
服务器端GroupsController
def show
@group = Group.find(params[:id])
respond_to do |format|
format.xml { render :xml => @group.to_xml(:include => :customers) }
end
end
Run Code Online (Sandbox Code Playgroud)
客户端模型
class Customer < ActiveResource::Base
end
class Group < ActiveResource::Base
end
Run Code Online (Sandbox Code Playgroud)
客户端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
Run Code Online (Sandbox Code Playgroud)
客户端视图:从Group对象访问客户
# access customers using attributes method.
@group.customers.each do |customer|
# access customer fields.
end
Run Code Online (Sandbox Code Playgroud)
客户端:将客户设置为组对象
group.attributes['customers'] ||= [] # Initialize customer array.
group.customers << Customer.build
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6552 次 |
| 最近记录: |