It looks like the default :id is the integer, can I make it as a string?
Asked
Active
Viewed 1,855 times
1
-
3do you have a specific reason for that? – x6iae Nov 13 '15 at 21:32
-
Check this. http://stackoverflow.com/questions/1200568/using-rails-how-can-i-set-my-primary-key-to-not-be-an-integer-typed-column – Padhu Nov 13 '15 at 21:46
2 Answers
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
-
-
Here is a post that explains it perfectly :) http://stackoverflow.com/questions/18704290/what-does-force-true-mean-in-the-schema-file – Cyzanfar Nov 17 '15 at 16:59
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:
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:
- Rails 4. Migrate table id to UUID
- http://www.lshift.net/blog/2013/09/30/changing-the-primary-key-type-in-ruby-on-rails-models/
--
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