简体   繁体   中英

many-to-many relationship in rails

I have the following models

class Order < ApplicationRecord
  has_many :order_details
  has_many :products, through: :order_details
end

class OrderDetail < ApplicationRecord
  belongs_to :order
  belongs_to :product
end

class Product < ApplicationRecord
  has_many :order_details
  has_many :orders, through: :order_details
end

And I already have product records in my database. Now, if using syntax: Order.create name: 'HH', product_ids: [1,2]

1 Order record is created, and rails automatically creates 2 more OrderDetail records to connect that Order record with 2 Products.

This syntax is quite handy.

Now, I want to learn more about it from the Rails documentation. But now i still can't find the documentation about it. Can someone help me find documents to learn more?

[Edit] Additional: I'd like to find documentation on the Rails syntax that allows passing a list of ids to automatically create records in the intermediate table, like the Order.create syntax with ```product_ids` `` that I gave above.

The extensive documentation is at https://api.rubyonrails.org/

And many-to-many is here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM