Search code examples
ruby-on-railsrubyruby-on-rails-3arel

Arel Aggregations, Count, Outer Join?


I have a Fact model, which has_many :votes. Votes also have a user_id field. I'd like to express the following in a scope for the Fact model: Give me all Facts which have 0 votes with a user_id equal to X.

I'm not quite familiar enough with Arel to understand how I might tackle this. Ideas?


Solution

  • I ended up solving this problem with the following scope:

      scope :not_voted_on_by_user, lambda {|user_id| select("distinct `facts`.*").joins("LEFT JOIN `votes` ON `facts`.id = `votes`.fact_id").where(["votes.user_id != ? OR votes.user_id IS NULL",user_id])}