1

It looks like the default :id is the integer, can I make it as a string?

Adam Lee
  • 24,710
  • 51
  • 156
  • 236

2 Answers2

5

Yes you can.

First run a migration:

create_table 'table' id: false, force: true do |t|
  t.string 'id', null: false
end

specifying the type string for the id.

Then in your model:

class Table < ActiveRecord::Base
  self.primary_key = :id
end

Which will basically explicitly indicate that the string id is the primary key of the object instance.

Cyzanfar
  • 6,997
  • 9
  • 43
  • 81
1

You should also consider looking up about uuid's in Rails.

Despite it being mainly a PostgreSQL piece of functionality, we've found it works well with MYSQL too:

enter image description here

You can set it up like this:

#app/models/post.rb
class Post < ActiveRecord::Base
   before_create :set_uuid

   private

   def set_uuid
      self.uuid = loop do
        random_token = SecureRandom.hex(5)
        break random_token unless self.class.exists? random_token
      end
   end
end

This can be accompanied - as pointed out by Cyzanfar - by replacing the id primary key with uuid. Rails 4 automatically supports uuid...

def change
   create_column :posts, :uuid, :string
   remove_column :posts, :id
   rename_column :posts, :uuid, :id
   execute "ALTER TABLE table ADD PRIMARY KEY (uuid);"
end

Some references:

--

Because Rails 4 supports uuid out of the box, this should work for you.

As mentioned, we use uuid for some of our models (it allows us to maintain functionality whilst keeping records unique)

Community
  • 1
  • 1
Richard Peck
  • 76,116
  • 9
  • 93
  • 147