2012-04-09 35 views
5

如何爲我的IdClient字段設置主鍵?我試過所有的方法,但我會得到錯誤(rails 3.0.9)...你能幫我嗎?如何在Rails遷移中設置ruby中的主鍵?

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 

另外如何在模型中設置關係?

回答

16

不要這樣做。使用內置的id字段作爲主鍵。如果你打算使用Rails,你應該用「Rails方式」構建應用程序,除非你有很好的理由不要。

如果你真的想這樣做,你可以傳遞一個:primary_key選項create_table

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

您還需要通過告訴你的模型的主鍵的名稱self.primary_key = "idClient"

+0

但爲什麼沒有?所以我不再需要我的領域idclient? – byCoder 2012-04-10 06:26:57

+0

@ ovatsug25你看完我的回答了嗎?這將包括我提到的「*非常好的理由*」。 – meagar 2013-01-25 15:22:12

+0

ohhh,我知道...謝謝你指出技術......但我仍然不想這樣做...... – ovatsug25 2013-01-25 16:27:48