【问题标题】:If I use :class_name attribute to has_one, what do I put in the migration?如果我对 has_one 使用 :class_name 属性,我应该在迁移中添加什么?
【发布时间】:2010-01-30 06:36:31
【问题描述】:

我的 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

谢谢!

【问题讨论】:

    标签: ruby-on-rails migration reference has-one


    【解决方案1】:

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

    在迁移中你可以使用:

    t.references :foo
    

    或:

    t.integer :foo_id
    

    任何一个都可以。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-18
      • 2015-08-26
      • 1970-01-01
      • 1970-01-01
      • 2014-09-15
      • 2013-05-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多