6

アソシエーションを使用しようとしている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では機能しないようです。

私が「協会」について見つけた1つの提案は、ただ方法を持っているということです

def customers
  Customer.find(:all, :conditions => {:group_id => self.id})
end

しかし、これには、それらの顧客を検索するために2回目のサービスコールを行うという欠点があります...クールではありません

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

クライアント側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
于 2010-04-28T23:10:16.267 に答える