[英]Show records common to two active record queries
我的 rails 應用程序中有一個搜索功能,可以通過game
或tag
搜索用戶。 游戲和標簽has_and_belong_to_many
用戶。
我想搜索一個game
和一個tag
以僅顯示同時擁有該游戲和標簽的用戶。
我可能可以在view
過濾結果,但我認為這仍然會導致查詢運行和服務器負載?
搜索模型:
users = User.all
users =
tu = Tag.includes(:users).where(["name like ?", "%#{user_profile_tag}%"])
gu = Game.includes(:users).where(["name like ?", "%#{game}%"])
users = (tu + gu)
return users
end
我有點不知所措,我嘗試在tu and gu
之間使用&
,但為此沒有列出任何用戶。
搜索控制器:
def new
@search = Search.new
@game = User.includes(:game).where(game: { name: @game })
@user_profile_tag = User.includes(:tag).where(tag: { name: @user_profile_tag })
end
任何想法都非常感謝!
編輯:模型關聯
class User < ActiveRecord::Base
has_and_belongs_to_many :games
has_and_belongs_to_many :tags
class Tag < ActiveRecord::Base
has_and_belongs_to_many :users
class Game < ActiveRecord::Base
has_and_belongs_to_many :users
您是否嘗試過同時應用這兩個條件?
users = User.joins(:games, :tags)
.where(games: { name: @game }, tags: { name: @user_profile_tag })
這應該返回同時擁有名稱為@game
游戲和名稱為@game
標簽的@user_profile_tag
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.