Forum: Ruby on Rails Using before_create and conflicting setter method...

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.
2ad5c7fd94f2d112c3dd2678cecc66c3?d=identicon&s=25 Brett Walker (Guest)
on 2006-04-21 22:12
(Received via mailing list)
Hi,

I am having trouble using before_create when I have an specialized
setter method:

   before_save     :set_campaign_start


#-----------------------------------------------------------------------
-------
   def set_campaign_start
     self.campaign_start = Time.now
   end

   # We want the date to always start at midnight

#-----------------------------------------------------------------------
-------
   def campaign_start=(new_time)
     @campaign_start = new_time.utc.at_beginning_of_day
   end

It sets @campaign_start in the object, but not the actual attribute,
and therefore not in the DB.  If I remove the setter method, the
before_create works great.  What is the correct way to do this?

Thanks,
Brett
13ea48f056b19349027d2f4a6921a46a?d=identicon&s=25 Jean-François (Guest)
on 2006-04-21 22:46
(Received via mailing list)
Hello Brett,
>    end
> and therefore not in the DB.  If I remove the setter method, the
> before_create works great.  What is the correct way to do this?

def campaign_start=(new_time)
  write_attribute("campaign_start", new_time.utc.at_beginning_of_day)
end

But I'm not sure I've understood your pb correctly.

    -- Jean-François.
3aaa40ee161275eb192b2895ca7c866b?d=identicon&s=25 Brett Walker (Guest)
on 2006-04-22 17:10
(Received via mailing list)
Jean-François,

>>      self.campaign_start = Time.now
>>
>> It sets @campaign_start in the object, but not the actual attribute,
>> and therefore not in the DB.  If I remove the setter method, the
>> before_create works great.  What is the correct way to do this?
>
> def campaign_start=(new_time)
>   write_attribute("campaign_start", new_time.utc.at_beginning_of_day)
> end
>
> But I'm not sure I've understood your pb correctly.

That did the trick.  Most examples I had seen showed using the
instance variable when overriding the assignment method.  But I guess
since I'm trying to do an assignment in the before_create, some
connection was not made yet.  The "campaign_start" attribute was not
getting set, just the instance variable.

Anyway, worked like a charm.  Thanks!

Brett_______________________________________________
Rails mailing list
Rails@lists.rubyonrails.org
http://lists.rubyonrails.org/mailman/listinfo/rails
This topic is locked and can not be replied to.