【问题标题】:t.belongs_to and the effect on postgresql DBt.belongs_to 和对 postgresql DB 的影响
【发布时间】:2013-09-05 21:25:03
【问题描述】:
class CreateCustomers < ActiveRecord::Migration
  def change
    create_table :customers do |t|
      t.belongs_to :user
      t.string :firstname
      t.string :surname
      t.timestamps
    end
  end

这些是我的模型:

class Customer < ActiveRecord::Base
    belongs_to :user
end

class User < ActiveRecord::Base
  has_many :customers
end

找到t.belongs_to :user 在数据库中添加外键。 但是当我用 pgadminIII 检查我的 postgre 数据库时,没有列出 foreign_key。 迁移添加了应有的 user_id,但没有列出 foreign_key。

对此有何解释?

最好的问候 否认

编辑:有关t.belongs_to的更多信息

create_table :accounts do |t|
  t.belongs_to :supplier
  t.string :account_number
  t.timestamps
end

这是一个例子。来自 railsguide 电子书第 2 章。

【问题讨论】:

  • 我通常使用 t.references :user, index: true 来处理这种情况,我知道它适用于 PG。

标签: ruby-on-rails postgresql ruby-on-rails-4 database-migration


【解决方案1】:

这是我第一次看到belongs_to 这个东西,但是要在迁移中的列上添加索引,您需要编写

t.belongs_to :user, index: true

(注意新的哈希语法)

【讨论】:

  • 谢谢你,它成功了。这个t.belongs_to 来自 railsguide 电子书。编辑我的帖子以获取更多信息。关于 t.belongs_to 事情
猜你喜欢
  • 2019-02-16
  • 1970-01-01
  • 1970-01-01
  • 2020-05-09
  • 1970-01-01
  • 2017-02-14
  • 2012-04-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多