I'm trying to use default values for a model in rails. The best documented way of doing this that I have seen is using the :default parameter in a migration. However, it looks like this only works for values. I am trying to set a default expression, specifically currval('customers_id_seq'::regclass)
. I can add the default expression by hand, but I can't figure out how to tell rails to use a default value. How can I use this default when creating model objects?
EDIT Here is a more specific example:
class CreateTestmodels < ActiveRecord::Migration
def up
create_table :testmodels do |t|
t.integer :idxfield, :null=>false
t.string :datafield
t.timestamps
end
execute("ALTER TABLE testmodels ALTER COLUMN idxfield SET DEFAULT currval('testmodels_id_seq'::regclass)")
end
def down
drop_table :testmodels
end
end
With this migration, I can run insert into testmodels (datafield) VALUES ('sometestdata');
, which will add a row to the table where idxfield
defaults to id
.
However, if I run Testmodel.create(:datafield=>"testdata")
from the rails console, it substitutes null for idxfield
and throws an exception.