如何在rails迁移时在ruby中设置主键?

byC*_*der 7 migration ruby-on-rails

如何为我的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
Run Code Online (Sandbox Code Playgroud)

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

mea*_*gar 19

不要这样做.使用内置id字段作为主键.如果你要使用Rails的,你应该建立你的应用程序中的"Rails的方式",除非你有非常充分的理由不这样做.

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

create_table :customers, :primary_key => :idClient do |t|
  # ...
end
Run Code Online (Sandbox Code Playgroud)

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