How to manage non-autoincrement primary key in Rails?
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 AThe 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 开发者_如何学Pythonmodel, 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.
Any suggestions?
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
精彩评论