[英]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.