Forum: Ruby on Rails default values

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Daniel Hernandez (Guest)
on 2006-05-03 21:07
(Received via mailing list)
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
Jeroen H. (Guest)
on 2006-05-03 21:07
(Received via mailing list)
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
Lugovoi N. (Guest)
on 2006-05-03 21:07
(Received via mailing list)
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
This topic is locked and can not be replied to.