哪个NOT IN()在连接上?

时间:2012-04-30 02:52:33

标签: ruby-on-rails ruby ruby-on-rails-3 activerecord

我在Rails模型中有以下范围。

class Suggestion < ActiveRecord::Base
  has_many :favourites

  def self.favoured_by(user)
    joins(:favourites).where(favourites: { user_id: user.id })
  end
end

完美无缺。它将返回特定用户喜欢的所有建议。

如何检索所有不受欢迎的建议或哪些建议受到青睐而不是这个特定用户?

def self.not_favoured_by(user)
  # ...
end

我的Favourite模型如下所示:

class Favourite < ActiveRecord::Base
  belongs_to :suggestion
  belongs_to :user
end

2 个答案:

答案 0 :(得分:4)

favorited_suggestions_ids = joins(:favourites).where(favourites: { user_id: user.id }).map(&:id)
return scoped if favorited_suggestion_ids.empty?
where('id not in (?)',favorited_suggestions_ids)

答案 1 :(得分:0)

这个怎么样:

def self.not_favoured_by(user)
  sql = <<-SQL
    SELECT suggestions.* FROM suggestions 
    WHERE NOT EXISTS 
      (SELECT id FROM favourites WHERE user_id = #{user.id} AND favourites.suggestion_id = suggestions.id);
  SQL
  find_by_sql(sql)
end