[英]Rails: Querying through 2 join table associations
我在模型之间有一个非常复杂的关系,现在对查询某些对象的SQL查询感到沮丧。
给定一个通过has_many:through关联和联合表分类连接到类别模型的产品模型 。 另外,一个用户模型通过has_many通过关联和联合表* category_friendship *连接到该类别模型 。
我现在面临着检索所有产品的问题,这些产品位于数组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
Category.rb
class Category < ActiveRecord::Base
has_many :categorizations
has_many :products, through: :categorizations
has_many :category_friendships
has_many :users, through: :category_friendships
分类
class Categorization < ActiveRecord::Base
belongs_to :category
belongs_to :product
Category_friendship.rb
class CategoryFriendship < ActiveRecord::Base
belongs_to :user
belongs_to :category
User.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
如果您需要更多详细信息来回答,请随时提问!
查看您已定义并简化的关联。 对我们必须实现的内容进行一些重构。
产品.rb
class Product < ActiveRecord::Base
belongs_to :category
end
User.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
Category.rb
class Category < ActiveRecord::Base
has_many :users, through: :category_friendships
has_many :products
def get_products
products
end
end
CREATING CATEGORY_FRIENDSHIP模型只连接表的NO需要的是需要具有NAME CATEGORIES_FRIENSHIPS这将只是USER_ID和CATEGORY_ID
用法:已更新
控制者
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
我赞成Ankits的答案,但我意识到有一种更优雅的处理方式:
给出:
u = User.first
uc = u.category_ids
然后我可以使用以下方法从类别中检索产品:
products = Product.joins(:categories).where('category_id IN (?)', uc)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.