Reputation: 1701
I need to deal with legacy db issues and I noticed that Rails always set the first element of a model with id = 1 and not zero.
Why is that?
class Car < ActiveRecord::Base
attr_accessible :name
end
In rails c
> c = Car.new(name: "Subaru")
> c.id
# id = 1
Upvotes: 1
Views: 121
Reputation: 106403
These - index of an array element and id of a record - are quite different concepts.
The first one is related to the pointer arithmetic. As we (usually) store the very first element of an array right at its beginning, to address it we need to add exactly 0 to the address of array itself. ) The next (second) element will be placed at &array + 1 size of element block, the next (third) - at &array + 2 sizes and so on.
The auto_increment id of a record is just that - id of a record, that should be higher (by some step value) than the previous one. Again, I think it's easier to describe this in terms of (the previous one when no 'previous ones' exist = 0) than with some artificial rule. And 0 + 1 is just that - 1.
Upvotes: 0
Reputation: 19041
This is simply following decades of convention in database.
Major RDBMS start their primary key from 1, not 0.
Upvotes: 2