当作为生成器参数传递时,belongs_to in 只是 references 的别名,它告诉 Rails 创建一个名为 blog_id 的列,它是一个外键:
# rails generate model Post blog:belongs_to
class CreatePosts < ActiveRecord::Migration[5.0]
def change
create_table :posts do |t|
t.belongs_to :blog, foreign_key: true
t.timestamps
end
end
end
这是定义两个表之间关系的实际数据库列。
它还将关联添加到模型中:
class Post < ApplicationRecord
belongs_to :blog
end
为什么has_many 不一样?
模型生成器的参数是模型的属性。 blog_id 是由数据库列支持的实际属性。
has_many 不是属性。这是一种元编程方法,可将posts 方法添加到您的博客实例。您需要手动将其添加到模型中。
如果你运行rails g model Blog posts:has_many foo:bar,Rails 实际上会使用这些属性创建迁移:
class CreateBlogs < ActiveRecord::Migration[5.0]
def change
create_table :blogs do |t|
t.has_many :posts
t.bar :foo
t.timestamps
end
end
end
Rails 不对参数进行类型检查。当然迁移实际上不会运行:
undefined method `has_many' for #<ActiveRecord::ConnectionAdapters::PostgreSQL::TableDefinition:0x007fd12d9b8bc8>
如果您已经生成迁移,只需删除行 t.has_many :posts 并将 has_many :posts 添加到 app/models/blog.rb。