LoginSignup
1
1

More than 5 years have passed since last update.

【Rails】relationテーブルの条件でthrough先を抽出

Posted at

relationテーブルの条件でthrough先を抽出

ユーザーがイベントに参加する状況を考えているような、以下の3つのテーブルがあるとする。
approvedはユーザーがイベントに参加することを承認されているかがboolで持っている。
この時にイベントごとに承認済みユーザー、未承認ユーザーを抽出したい。

スクリーンショット 2017-09-19 10.15.11.png

whereで以下のように条件を指定してしまうと、抽出後のusersでapprovedの条件を評価してしまい、カラムが存在しないというエラーになってしまう。

event_error.rb
has_many :approved_users, -> { where approved: true }, through: :relations, source: :user

解決策

以下のようにワンクッション挟むことで解決。

event.rb
  has_many :approved, -> { where approved: true }, class_name: "Relation"
  has_many :unapproved, -> { where approved: false }, class_name: "Relation"
  has_many :approved_users, through: :approved, source: :user
  has_many :unapproved_users, through: :unapproved, source: :user
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1