您好我正在寻找一种方法来查询这4个表,以获得与rails 4中用户选择的类别匹配的唯一产品。
Rails模型
class User < ActiveRecord::Base
has_many :categories, through: :user_categories
has_many :user_categories
end
class Product < ActiveRecord::Base
has_many :categories, through: :product_categories
has_many :product_categories
end
class Category < ActiveRecord::Base
has_many :users
has_many :products
end
class UserCategory < ActiveRecord::Base
belongs_to :user
belongs_to :category
end
class ProductCategory < ActiveRecord::Base
belongs_to :product
belongs_to :category
end
表格结构
products
+---------------+
| id | name |
+---------------+
| 1 | mouse |
| 2 | keyboard |
| 3 | iphone 6 |
+---------------+
categories
+---------------+
| id | name |
+---------------+
| 1 | computer |
| 2 | mobile |
+---------------+
users
+-----------+
| id | name |
+-----------+
| 1 | foo |
| 2 | bar |
+-----------+
product_categories
+------------------+
| id | p_id | c_id |
+------------------+
| 1 | 1 | 1 |
| 2 | 3 | 2 |
+------------------+
user_categories
+------------------+
| id | u_id | c_id |
+------------------+
| 1 | 1 | 1 |
+------------------+
答案 0 :(得分:2)
你的意思是这样的?
@user_categories_ids = User.first.categories.map(&:id)
Product.includes(:categories).where(categories: { id: @user_categories_ids })
如果您已正确设置关联,这应该有效。
如果您之后未使用类别关联,那么在性能方面,最好使用joins()
或joins().distinct()
代替includes()
联接示例:
Product.joins(:categories).where(categories: { id: @user_categories_ids })
如果您想要独特的结果
Product.joins(:categories).where(categories: { id: @user_categories_ids }).distinct # .uniq should also work I guess.