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

Answers


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

Need Your Help

How to optimize modular flash apps (load time & flexibility)?

flash actionscript-3 optimization module

I'm working on a large application that is broken up into many independent swfs. There is a master swf that loads a navigation shell and the foundational logic, and a module loading system that loads

Showing near guesses that exist in the grammar?

c# speech-recognition speech sapi

Microsoft SAPI SpeechRecognitionEngine as you know, is not the most accurate speech recognition engine out there. In the event of the program not recognizing the speech correctly, is there a way fo...