1

画像は私のデータモデルの一部を示しています。ユーザーに関連付けられているすべてのアイテムを(組織およびitems_groupを介して)フェッチしたいと思います。モデルを変更して、このクエリをコントローラーに書き込むにはどうすればよいですか?:through =>組織を使用すると、すべてのitems_groupsを取得できますが、クエリ関連アイテムにもう1つのリレーションを含める方法はありません。

ここに画像の説明を入力してください

class User < ActiveRecord::Base           
  has_and_belongs_to_many :organizations
  has_many :items_groups, :through => :organizations         
end

class Organization < ActiveRecord::Base
  has_and_belongs_to_many :users
  has_and_belongs_to_many :items_groups
  has_many :items, :through => :items_groups  
end

class ItemsGroup < ActiveRecord::Base  
  has_many :items, :inverse_of => :items_group
  has_and_belongs_to_many :organizations
  has_many :users, :through => :organizations             
end
4

2 に答える 2

4

バックツーフロントで実行し、ユーザーに結合されたアイテムを見つける必要があると思います。

User クラスで次のようなメソッドを定義できます。

def items
  Item.joins(:items_group => {:organizations => :users}).where("users.id" => self.id).select("distinct items.*")
end

それが返すアイテムは、明示的であるため読み取り専用になりますが、select個々のアイテムを複数回返さないようにする必要があると思います。

于 2012-10-25T20:58:27.713 に答える
0

モデルに関係を設定すると、これは機能するはずです:

users.organizations.item_groups.items

それが機能するためには、モデルにこれが含まれている必要があります:

class User < ActiveRecord::Base         
  has_many :organizations, :through => :organization_users
end

class Organization < ActiveRecord::Base
  has_many :item_groups, :through => :items_groups_organizations
end

class ItemsGroup < ActiveRecord::Base  
  belongs_to :item
end

それがあなたのために働くことを願っています!

于 2012-10-25T19:29:21.757 に答える