Forum: Ruby on Rails default column values and creating new rows with ActiveRecor

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.
7ac9652c07e2ce83b8288663460f5fa8?d=identicon&s=25 Christopher J. Bottaro (Guest)
on 2007-05-25 07:46
(Received via mailing list)
Hello,
I have a table that looks kind of like this:
CREATE TABLE blahs (
id SERIAL PRIMARY KEY,
...
modified_at DATETIME NOT NULL DEFAULT now()
)

When I try to create a new row using ActiveRecord, it bombs saying I'm
not allowed to set modified_at to NULL.

new = Blah.new
new.some_field = some_value
new.save! # ERROR:  null value in column "modified_at" violates not-
null constraint (ActiveRecord::StatementInvalid)

Is there any way to let ActiveRecord use the default value set at the
database level?

I'm using Postgres 8.2.

Thanks for the help.
Cb98c59a6ff22c72676e756bbd28f266?d=identicon&s=25 Jacob Atzen (Guest)
on 2007-05-25 10:09
(Received via mailing list)
Christopher J. Bottaro wrote:
>
> new = Blah.new
> new.some_field = some_value
> new.save! # ERROR:  null value in column "modified_at" violates not-
> null constraint (ActiveRecord::StatementInvalid)
>
> Is there any way to let ActiveRecord use the default value set at the
> database level?
>
> I'm using Postgres 8.2.

I'm not sure if you can use the default from the database. But why are
you using modified_at instead of updated_at which Rails will handle for
you automatically?

Also, if you want to set a default value you could simply do so in a
before_save hook:

def before_save
   self.modified_at = Time.now
end

--
Cheers,
- Jacob Atzen
54077fb03c95861af85880218cf7aef2?d=identicon&s=25 Gokhan Arli (sylow)
on 2007-05-25 15:56
Instead of modified_at you can use updated_at as column name, rails
takes care of it internally.

of as Jacob before_save will work, just check if the value is blank?
first.

Gokhan
www.sylow.net
Jacob Atzen wrote:
> Christopher J. Bottaro wrote:
>>
>> new = Blah.new
>> new.some_field = some_value
>> new.save! # ERROR:  null value in column "modified_at" violates not-
>> null constraint (ActiveRecord::StatementInvalid)
>>
>> Is there any way to let ActiveRecord use the default value set at the
>> database level?
>>
>> I'm using Postgres 8.2.
>
> I'm not sure if you can use the default from the database. But why are
> you using modified_at instead of updated_at which Rails will handle for
> you automatically?
>
> Also, if you want to set a default value you could simply do so in a
> before_save hook:
>
> def before_save
>    self.modified_at = Time.now
> end
>
> --
> Cheers,
> - Jacob Atzen
This topic is locked and can not be replied to.