首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Rails ActiveResource关联

Rails ActiveResource关联
EN

Stack Overflow用户
提问于 2010-04-28 22:33:13
回答 1查看 6.8K关注 0票数 6

我有一些ARes模型(见下文),我正在尝试使用关联(这似乎完全没有文档,而且可能不可能,但我想尝试一下)

因此,在我的服务端,我的ActiveRecord对象将呈现如下

代码语言:javascript
复制
render :xml => @group.to_xml(:include => :customers)

(见下面生成的xml )

模型组和客户是HABTM

在我的ARes方面,我希望它能够看到<customers>属性并自动填充该Group的.customers属性,但是has_many等方法不受支持(至少据我所知)

因此,我想知道ARes是如何在XML上反射来设置对象的属性的。例如,在AR中,我可以创建一个def customers=(customer_array)并自己设置它,但这在ARes中似乎行不通。

我为“联想”找到了一个建议,那就是有一个方法。

代码语言:javascript
复制
def customers
  Customer.find(:all, :conditions => {:group_id => self.id})
end

但这有一个缺点,那就是它打第二个服务电话去查那些客户.不酷

--我希望我的ActiveResource模型能看到客户在ActiveResource中的属性,并自动填充我的模型。有人对此有任何经验吗??

代码语言:javascript
复制
# 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>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2010-04-28 23:10:16

ActiveResource不支持关联。但它并不妨碍您将复杂数据设置/从ActiveResource对象获取。以下是我将如何实现它:

服务器端模型

代码语言:javascript
复制
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

代码语言:javascript
复制
def show
  @group = Group.find(params[:id])
  respond_to do |format|
    format.xml { render :xml => @group.to_xml(:include => :customers) }
  end    
end

客户端模型

代码语言:javascript
复制
class Customer < ActiveResource::Base
end

class Group < ActiveResource::Base
end

客户端GroupsController

代码语言:javascript
复制
def edit
  @group = Group.find(params[:id])
end

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

客户端视图:从组对象访问客户

代码语言:javascript
复制
# access customers using attributes method. 
@group.customers.each do |customer|
  # access customer fields.
end

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

代码语言:javascript
复制
group.attributes['customers'] ||= [] # Initialize customer array.
group.customers << Customer.build
票数 16
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2733571

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档