2015-05-01 68 views
0

我正在構建一個Rails應用程序,它具有用戶模型,通過使用UserInterests連接模型的has_many:through關係連接到興趣模型。困難的軌道ActiveModel查詢

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

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

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

非常感謝

+1

顯示Mysql的 – rick

+0

的Mysql ::錯誤的完整的錯誤:無效使用組功能:SELECT' users'。* FROM'users' INNER JOIN'user_interests' ON'user_interests'.'user_id' ='users'.'id' WHERE(COUNT(user_interests)= 0或user_interests.interest_id IN(1)) – AdamP

回答

0

試試這個,

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

同樣的錯誤我害怕 - 我想這個問題是在使用COUNT函數而不是在Rails語法中。不幸的是,我的SQL知識不夠好! – AdamP

+0

@AdamP你在user_interests中有什麼?什麼是user_interests? column_name或數組? – rick

+0

在Rails中,UserInterest是一個使用has_many:through關係連接用戶和興趣的模型。 user_interests數據庫表具有user_id和interest_id的屬性。因此,我想要查找在我的興趣ID列表中包含interest_id的user_interests條目的用戶,或根本沒有與其關聯的user_interests的用戶。 – AdamP

0
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 
+0

謝謝,但我需要使用單個查詢,因爲我打算將它與其他查詢條件鏈接起來 – AdamP

0

這爲我工作 - 雖然它不是100%完美。

  1. 使用LEFT JOIN查詢user_interests_count字段添加到用戶提供了counter_cache
  2. 搜索:

    用戶= User.joins( 「LEFT JOIN user_interests ON user_interests.user_id = users.id」) 。哪裏( 「?(users.user_interests_count =)或user_interests.interest_id IN()?」,0,interest_ids)