11

How can I set primary key for my IdClient field? I have tried all methods, but I'll get errors (rails 3.0.9)... Could you help me?

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

Also how to set relations in model?

Nathan
  • 7,816
  • 8
  • 33
  • 44
byCoder
  • 3,462
  • 6
  • 28
  • 49

1 Answers1

27

Don't do this. Use the built-in id field as the primary key. If you're going to use Rails, you should build your app the "Rails way" unless you have very good reason not to.

If you really want to do this, you can pass a :primary_key option to create_table:

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

You'll also need to tell your model the name of its primary key via self.primary_key = "idClient"

user229044
  • 232,980
  • 40
  • 330
  • 338
  • but why no? So i dont need anymore my field idclient? – byCoder Apr 10 '12 at 06:26
  • 1
    Sometimes legacy tables have a different primary key than the standard "Rails way" of `id`. Override with caution since everyone else will not be expecting the change. Also, in newer versions of Rails, you also have to add `id: false` so that it won't try to create the `id` column. – Ken Mayer Jun 12 '18 at 20:34
  • 1
    I'd argue that as simple as "the primary key of the table shouldn't be called ID" (there might be a better suited column name) is a simple and valid reason – Francesco Belladonna Jan 25 '21 at 19:32
  • @FrancescoBelladonna Sorry, no, In Rails, that is *not* a valid reason. Rails is an opinionated framework, and you're expected (bordering on required) to follow its conventions if you want it to be useful for you. Rails assumes the primary key of your table is `id`, and if you're starting a new Rails app, you're expected to work with these conventions. If your opinion is different, then within the scope of Rails, your opinion is wrong by definition. – user229044 Jan 26 '21 at 01:49