如果我对 has_one 使用 :class_name 属性,我应该在迁移中放入什么?

发布于 2024-08-19 20:33:47 字数 512 浏览 2 评论 0原文

我的 Rails 应用程序中有一个模型,它使用 has_one:class_name 属性:

class Foo < ActiveRecord:Base
  has_one :main_bar, :class_name => "Bar"

  # ...
end

我现在有点不确定要在此类的迁移中添加什么内容。我可以使用参考文献吗? Rails 将寻找什么作为 :main_bar 的列名称?我可以这样做吗?

class CreateFoos < ActiveRecord::Migration
  def self.up
    create_table :foos do |t|
      t.references :main_bar
    end
  end

  def self.down
    drop_table :foos
  end
end

谢谢!

I have a model in my Rails app that uses the :class_name attribute for has_one:

class Foo < ActiveRecord:Base
  has_one :main_bar, :class_name => "Bar"

  # ...
end

I'm a bit unsure what to put in the migration for this class now. Can I use references? What will Rails be looking for as the column name for :main_bar? Can I do it like this?

class CreateFoos < ActiveRecord::Migration
  def self.up
    create_table :foos do |t|
      t.references :main_bar
    end
  end

  def self.down
    drop_table :foos
  end
end

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

怪我入戏太深 2024-08-26 20:33:47

您不会在表中放入任何具有“has_one”关系的内容。 foreign_key 位于另一个表中。在上面的示例中,您需要向 bars 表添加一个外键。

在迁移中,您可以使用:

t.references :foo

或:

t.integer :foo_id

两者之一都可以。

You don't put anything in the table with the "has_one" relationship. The foreign_key goes in the other table. In your example above, you'd need to add a foreign key to your bars table.

In the migration you can use:

t.references :foo

or:

t.integer :foo_id

Either one will work.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文