0

モデル間に非常に複雑な関係があり、いくつかのオブジェクトを取得するための 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

回答に詳細が必要な場合は、お気軽にお問い合わせください。

4

2 に答える 2

0

定義した関連付けを見て、物事を単純化します。達成しなければならないことを少しリファクタリングします。

製品.rb

class Product < ActiveRecord::Base

  belongs_to :category

 end

ユーザー.rb

  class User < ActiveRecord::Base
        has_many :categories, through: :category_friendships
        scope :all_data , includes(:categories => [:products])

   def get_categories
     categories
   end

   def feed
      all_products = Array.new
      get_categories.collect {|category| category.get_products }.uniq
   end
  end

カテゴリー.rb

class Category < ActiveRecord::Base
 has_many :users, through: :category_friendships
 has_many :products

 def get_products
   products
 end
end

CATEGORY_FRIENDSHIP モデルを作成する必要はありません。名前 CATEGORIES_FRIENSHIPS を持つ結合テーブルのみが必要です。

使用法: 更新

コントローラ

  class UserController < ApplicationController
         def index
           @all_user_data = User.all_data
        end
   end

index.html.erbを見る

<% for user in @all_user_data %>
 <% for products in user.feed %>
  <% for product in products %>
       <%= product.name %>
     end
  end
end
于 2012-09-04T12:02:11.437 に答える
0

私はAnkitsの回答に賛成しましたが、これを処理するよりエレガントな方法があることに気付きました:

与えられた:

u = User.first
uc = u.category_ids

次に、次を使用してカテゴリから製品を取得できます。

products = Product.joins(:categories).where('category_id IN (?)', uc)
于 2012-09-05T12:23:15.667 に答える