在"引用"迁移中指定列名称

caa*_*os0 113 activerecord ruby-on-rails rails-migrations ruby-on-rails-3

我想migration在Rails中创建一个引用另一个表.通常,我会这样做:

add_column :post, :user, :references
Run Code Online (Sandbox Code Playgroud)

这将创建一个名为列user_idposts表中.但是,如果,而不是user_id,我想要的东西author_id呢?我怎样才能做到这一点?

eco*_*gic 242

Rails 4.2+中你也可以在db中设置外键,这是一个好主意.

对于简单的关联,这也可以在t.references添加时完成foreign_key: true,但在这种情况下,您将需要两行.

# The migration
add_reference :posts, :author, index: true
add_foreign_key :posts, :users, column: :author_id

# The model
belongs_to :author, class_name: "User"
Run Code Online (Sandbox Code Playgroud)

  • 我不确定你需要`add_reference`调用中的`references :: users`选项.我没有在文档中看到它,并且它似乎在没有它的情况下工作. (4认同)
  • 谢谢,但问题是标记为Rails3,我很乐意帮忙 (2认同)
  • 哦,我没注意到.嗯,这对我来说非常有帮助.:) (2认同)
  • 当我看到这个的时候,我几乎放弃了希望!谢谢@ecoologic! (2认同)
  • @ecoologic,你可能只想添加一件事,add_foreign_key只有4.2+版本.;) (2认同)
  • 查看源代码,它确实对可选的“references”参数没有任何作用。而且我认为它的设置方式如果没有名为“authors”的表并不重要,它所做的只是添加一个名为“author_id”的列。如果你想创建一个外键约束,它*确实*重要,因为它确实尝试使用它作为表名,所以如果你想这样做,你必须有一个单独的 add_foreign_key 语句。 (2认同)

She*_*yar 211

适用于Rails 5+

初步定义:

如果您要定义Post模型表格,您可以设置references,indexforeign_key在一行:

t.references :author, index: true, foreign_key: { to_table: :users }
Run Code Online (Sandbox Code Playgroud)

更新现有:

如果要添加对现有表的引用,则可以执行以下操作:

add_reference :posts, :author, foreign_key: { to_table: :users }
Run Code Online (Sandbox Code Playgroud)

注意: 默认值为indextrue.

  • 这个定义允许`null`。要不允许它们,请添加通常的选项`null:false`。 (2认同)

nat*_*vda 85

在rails 4中,当使用postgresql和schema_plus gem时,你可以写

add_reference :posts, :author, references: :users
Run Code Online (Sandbox Code Playgroud)

这将创建一个author_id正确引用的列users(id).

在你的模型中,你写

belongs_to :author, class_name: "User"
Run Code Online (Sandbox Code Playgroud)

  • 如果你使用`create_table`:`t.references:author,references :: users` (28认同)
  • 在 Rails 6 中,语法 `t.references :col_name,references: other_table_name` 似乎不需要安装额外的 gems 就可以工作。 (3认同)
  • 将@ MichaelRadionov的评论添加到您的答案将使其完美. (2认同)
  • 我一直在看Rails 4.1源代码,我找不到任何证据表明`:references`实际上做了什么. (2认同)

msc*_*ltz 55

手动完成:

add_column :post, :author_id, :integer
Run Code Online (Sandbox Code Playgroud)

但现在,当你创建belongs_to语句时,你将不得不修改它,所以现在你必须调用

def post
    belongs_to :user, :foreign_key => 'author_id'
end
Run Code Online (Sandbox Code Playgroud)


jes*_*199 49

如果您没有使用外键,那么另一个表的实际表名是什么并不重要.

add_reference :posts, :author
Run Code Online (Sandbox Code Playgroud)

从Rails 5开始,如果您使用的是外键,则可以在外键选项中指定其他表的名称.(有关讨论,请参阅https://github.com/rails/rails/issues/21563)

add_reference :posts, :author, foreign_key: {to_table: :users}
Run Code Online (Sandbox Code Playgroud)

在Rails 5之前,您应该将外键添加为单独的步骤:

add_foreign_key :posts, :users, column: :author_id
Run Code Online (Sandbox Code Playgroud)

  • to_table是复数形式:`{to_table :: users}` (12认同)