1

我在 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
4

2 回答 2

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)
于 2012-04-30T03:02:37.000 回答
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
于 2012-04-30T03:01:31.380 回答