rails: create a single table without id
I've just generat开发者_运维知识库ed my first scaffold in rails. Now, I don't want my table to have a field named "id". Instead I want it to be named "uid" which will be an arbitrary string. But I can't seem to get my head around how this is to be done. Especially with managing routes. I've managed to set :id=>false and define "uid" as the primary key but the controller fails because it still tries to lookup by id. How do I handle this?
Also, anything else I'm not aware of that might blow?
And, I know rails is all about convention and all and I must not try to go against "the rails way", but I really want this thing to work this way.
In your migration update your code like this:
create_table :table_name, :primary_key => :uid do |t|
...
end
And your model should include this line:
class ModelName < ActiveRecord::Base
set_primary_key :uid
end
All will be working same as with normal id column.
Model.find will find by uid, not id and etc ...
You should be able to find records by doing:
@record = Model.find('foo')
or
@record = Model.find_by_uid('foo')
be sure that in your migration file you have:
create_table :table_name, :primary_key => :uid do |t|
...
then insert in your model:
self.primary_key = "uid"
and find your record as John Topley says:
@record = Model.find('foo')
This should work
The existing answers are, although great for older versions, outdated, so here is the update:
(Built on top of retro's +1 answer:)
Migration:
create_table :table_name, id: false, :primary_key => :uid do |t|
...
end
Model:
class ModelName < ActiveRecord::Base
self.primary_key= :uid
end
Note: I believe this change goes back to ~ rails 3, however I am not 100% certain about this.
Happy codin .
精彩评论