【问题标题】:How to set primary key in ruby on rails migration?如何在 ruby​​ on rails 迁移中设置主键?
【发布时间】:2012-04-09 20:13:42
【问题描述】:

如何设置 IdClient 字段的主键?我已经尝试了所有方法,但我会得到错误(rails 3.0.9)...你能帮帮我吗?

class CreateCustomers < ActiveRecord::Migration
  def self.up
    create_table :customers do |t|
      t.integer :IdCustomer
      t.string :username
      t.string :crypted_password
      t.string :password_salt
      t.string :persistence_token
      t.string :email
      t.string :Skype
      t.string :ICQ
      t.string :Firstname
      t.string :Lastname
      t.string :Country
      t.string :State
      t.string :City
      t.string :Street
      t.string :Building
      t.integer :Room
      t.string :AddressNote
      t.date :DateOfReg
      t.integer :CustGroup
      t.float :TotalBuy

      t.timestamps
      add_index(:customers, :IdCustomer, :unique => true)
    end
  end

  def self.down
    drop_table :customers
  end
end

还有如何在模型中设置关系?

【问题讨论】:

    标签: ruby-on-rails migration


    【解决方案1】:

    不要这样做。使用内置的id 字段作为主键。如果您打算使用 Rails,您应该以“Rails 方式”构建您的应用程序,除非您有非常充分的理由不这样做。

    如果你真的想这样做,可以将:primary_key 选项传递给create_table

    create_table :customers, :primary_key => :idClient do |t|
      # ...
    end
    

    您还需要通过self.primary_key = "idClient" 告诉您的模型其主键的名称

    【讨论】:

    • 但为什么不呢?所以我不再需要我的字段 idclient 了吗?
    • 有时旧表的主键与id 的标准“Rails 方式”不同。谨慎覆盖,因为其他所有人都不会期待更改。此外,在较新版本的 Rails 中,您还必须添加 id: false 以便它不会尝试创建 id 列。
    • 我认为“表的主键不应该称为 ID”(可能有更合适的列名)这样简单是一个简单而有效的理由
    • @FrancescoBelladonna 抱歉,不,在 Rails 中,这不是正当理由。 Rails 是一个固执己见的框架,如果您希望它对您有用,您应该(几乎是必需的)遵循它的约定。 Rails 假设你的表的主键是id,如果你正在启动一个新的 Rails 应用程序,你应该使用这些约定。如果你的意见不同,那么在 Rails 的范围内,你的意见是错误的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-14
    相关资源
    最近更新 更多