views:

295

answers:

1

I have lots of situations where I'd like to have a non-autoincrement primary key when using Rails.

Example: I have one-to-one relationship between A and B. B describes some specific features added to A thus can't exist without A. So we have:

A has one B
B belongs to A

The natural thinking would be having B.A_id as primary key. So I tried create_table b, :id=>false in migration and set_primary_key :a_id in B's model, but it doesn't create actual primary keys in the database. And I want them (as well as foreign keys), as the database will be used not only by this Rails app.

If I create primary keys with execute they don't land in schema.rb, which hurts. Now I'm thinking about a workaround: I can live without PK constraint as long as there's unique constraint for that column, so I can use Rails' add_index in the migration which seems more elegant.

But generally I'm guessing I went into a counter-Rails corner of doing things. I wonder why? Are people really not willing to have constraints in their databases under the hood of Rails? [troll mode on] Why use SQL then, only because it's still the most popular storage on the market now? [troll mode off]

But seriously, I like ActiveRecord mostly because migrations provide nice change management of the model. I don't want to get rid of it. It's just AR has some magic which is a bit different magic than I would typically want to use.

Any suggestions?

+1  A: 

A very similar question on StackOverflow suggests trying something like:

create_table(:b, :id => false) do |t|
  t.integer :a_id, :options => 'PRIMARY KEY'
end
Conspicuous Compiler