Re: Suggestion: default values for models

Matt Jones
Thu, 18 Oct 2012 18:21:57 -0000

On Oct 18, 2012, at 8:50 AM, Gabriel Sobrinho wrote:

> That is a problem for me either.
>
> I can''t use before_save callback because I need to show the
default value on forms.
>
> So, I have a date field and the default value is today, but when user open
the form, today must be on that field.
>
>
> I''m setting this kind of default value on controller like that:
>
> def new
>   @payment = Payment.new
>   @payment.date = Date.current
> end

One method I was surprised to not see on Stack Overflow - overriding the
accessor:

class Payment < AR::Base

  def date
    super || write_attribute(:date, Date.current)
  end

end

This still has the issue identified by G. Sobrinho, however, where explicitly
setting an attribute to nil doesn''t work quite right.

--Matt Jones