モデル間に非常に複雑な関係があり、いくつかのオブジェクトを取得するための SQL クエリに不満を感じています。
has_many :through アソシエーションとジョイント テーブルcategorizationを介してカテゴリ モデルに接続されたProduct モデルが与えられます。また、has_many :through アソシエーションと結合テーブル *category_friendship* を介して、このカテゴリ モデルに接続されたUser モデル。
現在、配列 user.category_ids のカテゴリ内にあるすべての製品を取得するという問題に直面しています。ただし、WHERE ステートメントを適切に記述できないわけではありません。
私はこれを試しました:
u = User.first
uc = u.category_ids
Product.where("category_id IN (?)", uc)
ただし、product テーブルに直接 category_id がないため、これは機能しません。しかし、これを変更してジョイント テーブルの分類を使用するにはどうすればよいでしょうか。
モデルの詳細を提供しています。私の質問に答えるのに役立つかもしれません。
製品.rb
class Product < ActiveRecord::Base
belongs_to :category
def self.from_users_or_categories_followed_by(user)
cf = user.category_ids
uf = user.friend_ids
where("user_id IN (?)", uf) # Products out of friend_ids (uf) works fine, but how to extend to categories (cf) with an OR clause?
end
カテゴリー.rb
class Category < ActiveRecord::Base
has_many :categorizations
has_many :products, through: :categorizations
has_many :category_friendships
has_many :users, through: :category_friendships
分類.rb
class Categorization < ActiveRecord::Base
belongs_to :category
belongs_to :product
Category_friendship.rb
class CategoryFriendship < ActiveRecord::Base
belongs_to :user
belongs_to :category
ユーザー.rb
クラス User < ActiveRecord::Base
has_many :category_friendships
has_many :categories, through: :category_friendships
def feed
Product.from_users_or_categories_followed_by(self) #this should aggregate the Products
end
回答に詳細が必要な場合は、お気軽にお問い合わせください。