[英]Rails has_many/belong_to Associations
With has_many
belongs_to
or any of the associations: 与
has_many
belongs_to
或任何关联:
No, it does not matter which one is created first as Rails will solve the correct order for you. 不,首先创建哪个无关紧要,因为Rails会为您解决正确的订单。
In case of a belongs_to / has_one association 如果是归属关系/ has_one关联
class Parent < ActiveRecord::Base
has_many :children
end
class Children < ActiveRecord::Base
belongs_to :parent
end
p = Parent.new(name: 'Jhon')
p.children << Children.new
p.save
(0.3ms) BEGIN
SQL (27.1ms) INSERT INTO `parents` (`name`) VALUES ('Jhon')
SQL (23.1ms) INSERT INTO `childrens` (`parent_id`) VALUES (7842)
(95.0ms) COMMIT
The relationships are set up in the models, after the tables are created. 创建表后,将在模型中建立关系。 Therefore, it doesn't matter which order your create the actual tables.
因此,创建实际表的顺序无关紧要。
I typically will create the more dominate of the two first, such as create User, and then any relations after. 我通常会先创建两个中最主要的一个,例如创建User,然后再创建任何关系。 But again, there isn't any reason to have an order to create them.
但是同样,没有任何理由要创建它们的命令。
You're talking about one to many relationship. 您正在谈论一对多的关系。
Parent has_many Children
and Child belongs_to Parent
Parent has_many Children
和Child belongs_to Parent
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.