Thanks for all the fish
Thanks for all the fish

Reputation: 1701

Why Ruby on Rails 3.2.8 - the first element in the model returns id = 1 instead of 0?

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

Answers (2)

raina77ow
raina77ow

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

Jason Kim
Jason Kim

Reputation: 19041

This is simply following decades of convention in database.

Major RDBMS start their primary key from 1, not 0.

Upvotes: 2

Related Questions