LoginSignup
44
52

More than 5 years have passed since last update.

Railsで多対多関連先のテーブルのカラムを指定する方法

Posted at

調べてみたところ、見当たらなかったので個人的メモも兼ねて書きました。

特に、多対多関連先のテーブルのカラムを条件に指定してwhereしたい場合についての記述がなかったので、個人的に詰まりました。

ActiveRecordで多対多のアソシエーションを結ぶにはhas_many_and_belongs_tohas_many :throughの2つの方法がありますが、今回はhas_many :throughで確認しているので、has_many_and_belong_toで同じように動くかは分かりません。

Modelの定義

Modelを以下のように定義します。

# app/models/order.rb
class Order < ActiveRecord::Base
  has_many :customers_orders
  has_many :customers, through: :custormers_orders
end

# app/models/customer.rb
class Customer < ActiveRecord::Base
  has_many :customers_orders
  has_many :orders, through: :custormers_orders
end

# app/models/customers_order.rb
class CustomersOrder < ActiveRecord::Base
  belongs_to :customer
  belongs_to :order
end

ordersとcustomersが多対多関連で、中間テーブルとしてcustomers_ordersがあります。

多対多関連先のテーブルの値を指定して一緒に保存したい場合

保存する場合はcustomer_ids: [1, 2]という指定ができ、簡単に指定ができます。

customer_idが1, 2のデータをインサートする。

> Order.create(customer_ids: [1, 2])

多対多関連先のテーブルのカラムを条件文に指定してデータを取得する場合

取得する場合は、customer_ids: [1, 2]といった指定の仕方はできませんので、以下のような書き方になります。

customer_idが1の時のorderを取得する。

> order = Order.includes(:customers).where(customer: { id: 1 })
44
52
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
44
52