2010-04-28 54 views
6

我有一些ARES模型(见下文),我试图用与协会(这似乎是完全无证,也许不可能,但我想我会试试看)的Rails的ActiveResource协会

所以,在我的服务端,我的ActiveRecord的对象将呈现类似

render :xml => @group.to_xml(:include => :customers) 

(见下面生成XML)

的模型组和客户是HABTM

在我的ARES方面,我希望能看到<customers> xml属性并自动填充该组对象的.customers属性,但不支持has_many等方法(至少据我所知)

所以我想知道ARes是如何反映XML的设置对象的属性。例如,在AR中,我可以创建一个def customers=(customer_array)并自己设置,但这在AR中似乎不起作用。

一个建议,我发现一个“协会”是只是有一个方法

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> 

回答

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.build