2010-04-28 51 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