belongs_to 是否在 Rails 5 中创建关联?
Does belongs_to creates an association in Rails 5?
我有以下型号:
class User
has_many :items
end
class Item
belongs_to :user
end
在 create_table
里面 items
我有:
t.belongs_to :person
我正在使用 Rails 5,我看到它会在 items
table 中自动为 person_id
创建一个索引。然而,根据这个SO thread,这是不应该发生的。
答案是否正确或是否已添加到 Rails 5(或某些 Rails 4.x 版本)?
Does belongs_to creates an association in Rails 5?
是的。
belongs_to
is an alias of references
并且它:
- 在
items
table 中创建 person_id
列;
- 在
person_id
列上添加索引。
不应该。
正如@Andrey 提到的,belongs_to
是references
的别名。如果您遵循文档,您会看到 references
在内部使用 connection.add_reference
。在 connection.add_reference
文档中,您可以看到 options,其中 index
:
:index
Add an appropriate index. Defaults to false.
See add_index for usage of this option.
因此,默认情况下,将索引添加到数据库的 index
选项设置为 false。您应该在 references
.
中明确设置它
我有以下型号:
class User
has_many :items
end
class Item
belongs_to :user
end
在 create_table
里面 items
我有:
t.belongs_to :person
我正在使用 Rails 5,我看到它会在 items
table 中自动为 person_id
创建一个索引。然而,根据这个SO thread,这是不应该发生的。
答案是否正确或是否已添加到 Rails 5(或某些 Rails 4.x 版本)?
Does belongs_to creates an association in Rails 5?
是的。
belongs_to
is an alias of references
并且它:
- 在
items
table 中创建person_id
列; - 在
person_id
列上添加索引。
不应该。
正如@Andrey 提到的,belongs_to
是references
的别名。如果您遵循文档,您会看到 references
在内部使用 connection.add_reference
。在 connection.add_reference
文档中,您可以看到 options,其中 index
:
:index
Add an appropriate index. Defaults to false.
See add_index for usage of this option.
因此,默认情况下,将索引添加到数据库的 index
选项设置为 false。您应该在 references
.