簡體   English   中英

顯示兩個活動記錄查詢共有的記錄

[英]Show records common to two active record queries

我的 rails 應用程序中有一個搜索功能,可以通過gametag搜索用戶。 游戲和標簽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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM