Rails: making a string the primary key in Rails 3
I'm trying to recreate a Sinatra app (using a recipe from a book) into Rails. The Sinatra app uses data_mapper which allows you to set the string as a primary key using using :key => true
include DataMapper::Resource property :identifier, String, :key => true property :created_at, DateTime
I'm not sure how to do this in Rails 3. Can you explain how I would set the identifier string as a primary key?
An additional problem might be that I'm developing on sqlite3 but will be hosting eventually on Heroku with 'pg.' If that complicates things too much, please just pretend I'm only working with sqlite3
Rails will find the column in the database which has the primary key and use that automatically. You just need to put it into the migration:
create_table :products do |t| t.string :identifier, :primary_key => true end
ActiveRecord will automatically point id to this column.
More information at http://guides.rubyonrails.org/migrations.html.
on rails 3.2+ you also need to pass id: false, something like this
create_table :products, id: false do |t| t.string :identifier, :primary_key => true end