ActiveRecord: Return All Records Without Association That Meets Criteria

时间:2015-07-28 22:52:56

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

This is more difficult than it sounds. How can I return all the records of one table that do not have any associated records that meet certain criteria?

For example, I want to get all users who do not have an address history that includes the city of Anchorage (no reason in particular, I love that town).

# models
class User
  has_many :addresses
end

class Address
  belongs_to :user
end

# query
# except this returns the wrong set
users = User.joins(:address).where.not(address: { city: 'anchorage' })
users.map { |u| u.addresses.map(&:city) }.flatten.uniq
=> ['detroit', 'anchorage', 'denver']

1 个答案:

答案 0 :(得分:0)

感谢SQL中的this answer,我能够创建一个返回Active Record集合的解决方案。

User.joins(" LEFT JOIN addresses a
             ON a.user_id = users.id
             AND a.city = 'seattle'
             WHERE a.city IS NULL ")