簡體   English   中英

困難的Rails ActiveModel查詢

[英]Difficult Rails ActiveModel Query

我正在構建一個具有用戶模型的Rails應用程序,並使用UserInterests聯接模型通過has_many:through關系將其聯接到興趣模型。

給定一組興趣,我想做的是找到所有在該組中至少選擇了一個興趣,或者根本沒有選擇任何興趣的用戶。 我在想這樣的事情:

users = users.joins(:user_interests).where(["COUNT(user_interests) = 0 OR user_interests.interest_id IN ?", interest_ids])

這將引發Mysql語法錯誤。 任何想法如何實現這一目標?

非常感謝

試試這個

users = User.joins(:user_interests).where("COUNT(user_interests) = 0 OR interest_id IN (?)", interest_ids)
class User < ActiveRecord::Base
  scope :with_interests, ->(*interests) {
    joins(:user_interests).where(user_interests: {interest_id: interests.flatten.compact.uniq})
  }

  scope :no_interests, -> {
    where("not exists (select * from user_interests ui2 where ui2.user_id = users.id)")
  }
end

interest = Interest.first

User.with_interests(interest) + User.no_interests

這對我有用-盡管不是100%理想。

  1. 使用counter_cache向用戶添加user_interests_count字段
  2. 使用LEFT JOIN查詢進行搜索:

    users = User.joins(“向左聯接user_interests on user_interests.user_id = users.id”)。where(“(users.user_interests_count =?)OR user_interests.interest_id IN(?)”,0,interest_ids)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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