Rails4 です。
Personモデルが複数の Emailモデルを持っているという has_many なアソシエーションで、ある特定の email を持っているいる人を除外したい。
とりあえず、除外でなく、持っている人を検索するなら……
@people_with_email = Person.all.includes(:emails).where("emails.email='xxx@xxx.com' or emails.email='yyy@yyy.com').references(:emails)
で良いようだ。
では、除外するには……
@people_except_email = Person.all.includes(:emails).where("emails.email != 'xxx@xxx.com' or emails.email != 'yyy@yyy.com'").references(:emails)
でよいか……どうも良くないみたいだ。
試行錯誤の結果以下のようにした。
ids = Person.connection.select_rows(Person.joins(:emails).where("emails.email = 'xxx@xxx.com' or emails.email = 'yyy@yyy.com'").select("people.id").to_sql) @people_except_email = Person.all.includes(:emails).where.not(:id => ids).references(:emails)
参考にさせていただいたサイトは以下です。本当に助かりました。ありがとうございます。