I have a model with 2 fields => :name and :age
I need to do a Migration that add a column :position which needs auto increment and start with 0 (zero).
I tried these way:
class AddPosition < ActiveRecord::Migration
def up
add_column :clientes, :position, :integer, :default => 0, :null => false
execute "ALTER TABLE clientes ADD PRIMARY KEY (position);"
end
But it doesn’t work because it not auto increment. If I try to use primary key as type:
class AddPosition < ActiveRecord::Migration
def up
add_column :clientes, :position, :primary_key, :default => 0, :null => false
end
end
rake db:migrate don’t run because multiple values.
Anyone could explain a way to have zeros and autoincrement on Primary Key w/ Rails 3.2?
Here’s how you can set up auto increment column in PostgreSQL:
But unfortunately it may not be what you need. The above would work if you’d insert values into
clientstable with SQL like this:INSERT INTO clients(name, age) VALUES('Joe', 21), and rails doesn’t work that way.The first problem is that rails expects primary key to be called
id. And while you can override this convention, it would cause more problems than it would solve. If you want to bind position to primary key value, better option is to add virtual attribute to your model, a method like this:But let’s suppose you already have conventional primary key
idand want to addpositionfield so that you can reorder clients after they have been created, without touching their ids (which is always a good idea). Here comes the second problem: rails won’t recognize and respectDEFAULT nextval('clients_position_seq'), i.e. it won’t pull values from PG backed sequence and would try to putNULLinpositionby default.I’d like to suggest looking at acts_as_list gem as better option. This would make DB sequence manipulations unnecessary. Unfortunately it uses
1as initial value forpositionbut that can be cured by setting custom name for list position field and defining method as I showed above.