Default values


#1

Hello,
I’m working with a postgresql table

CREATE TABLE elements (
id serial primary key,
c1 text default f1(),

cN text default fN()
);

But if I use de lines

@element = Element.new
@element.save

the values that element take are the nextval in the id field and nules
in
all the other fields.

How can I get the defaults?
(but without rewriting the funcitions f1,…,fN in the rails aplication,
of course)

Thaks

Daniel H


#2

Daniel Hernandez wrote:

But if I use de lines

@element = Element.new
@element.save

the values that element take are the nextval in the id field and nules
in all the other fields.

How can I get the defaults?
(but without rewriting the funcitions f1,…,fN in the rails aplication,

I don’t think ActiveRecord works very well with PG functions as
defaults, especially in production mode, you might want to search the
archives on that a little though…

HTH,

Jeroen


#3

You might look at http://dev.rubyonrails.org/ticket/2259 – I use this
approach occasionally,
my current version:

module ActiveRecord
class Base
def self.new_default
unless @default_sql_query || @no_defaults_sql
sql_query = <<-end_sql
select (pg_get_expr(adbin, adrelid) || ‘::’ ||
format_type(atttypid, atttypmod)
|| ’ as ’ || quote_ident(attname))::text as def_v
from pg_attribute left join pg_attrdef on
(attrelid = adrelid and adnum=attnum)
where attrelid = ‘#{table_name}’::regclass
and not attisdropped and attnum>0 and atthasdef
end_sql
res = connection.query(sql_query)
@no_defaults_sql = res.empty?
unless res.empty?
@default_sql_query = (res.collect {|r| r[0]}).join(’,’)
end
end
return self.new if @no_defaults_sql
row = connection.query(“SELECT #{@default_sql_query}”)[0]
data = self.new
row.keys.each { |name| data[name] = row[name] }
data
end
end
end