6

我有一些我正在尝试使用关联的 ARes 模型(见下文)(这似乎完全没有记录,也许不可能,但我想我会试一试)

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

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

(请参阅下面生成的 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

但这有一个缺点,它会拨打第二个服务电话来查找这些客户......不酷

我希望我的 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>
4

1 回答 1

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

客户端组控制器

def edit
  @group = Group.find(params[:id])
end

def update
  @group = Group.find(params[:id])
  if @group.load(params[:group]).save
  else
  end
end

客户视图:从 Group 对象访问客户

# access customers using attributes method. 
@group.customers.each do |customer|
  # access customer fields.
end

客户端:将客户设置为组对象

group.attributes['customers'] ||= [] # Initialize customer array.
group.customers << Customer.build
于 2010-04-28T23:10:16.267 回答