简体   繁体   English

Rails has_many / belong_to协会

[英]Rails has_many/belong_to Associations

With has_many belongs_to or any of the associations: has_many belongs_to或任何关联:

  1. Does it matter which object of the two models is created first? 首先创建两个模型的哪个对象有关系吗?
  2. Is there a convention, as to which should be created first? 是否有约定,应首先创建?

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 ChildrenChild belongs_to Parent

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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