【问题标题】:Rails ActiveResource AssociationsRails ActiveResource 关联
【发布时间】:2010-04-28 22:33:13
【问题描述】:

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

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

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

(见下方生成的 xml)

模型组和客户是HABTM

在我的 ARes 方面,我希望它可以看到 <customers> xml 属性并自动填充该 Group 对象的 .customers 属性,但不支持 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>

【问题讨论】:

    标签: ruby-on-rails associations activeresource


    【解决方案1】:

    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
    

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

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

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

    group.attributes['customers'] ||= [] # Initialize customer array.
    group.customers << Customer.build
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多