Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

This project is archived and is in readonly mode.

ActiveRecord.Base attribute accessor recommendation

#2616

The documentation for ActiveRecord::Base suggest overloading attribute accessors like this:

def length=(minutes)
  write_attribute(:length, minutes.to_i * 60)
end

Using this with update_attributes with { :length=>"6d" } will result in a silent conversion to 6, ignoring any validation. I haven't figured out the way to do this for integers (probably match against a regex) but for floats I'd use

def length=(minutes)

write_attributes(:length, Kernel.Float(minutes)*60.0)

recue ArgumentError

write_attributes(:length, minutes)

end

so that validation will still do their thing, etc.

Reported by Esben Mose Hansen · May 7th, 2009 @ 12:41 PM

State: stale
Milestone: 3.x
Assigned to: nobody
Importance: none

Activity

  1. Jeremy Kemper
    Jeremy Kemper
    • Milestone changed from 2.x to 3.x

    May 4th, 2010 @ 06:48 PM

  2. Rohit Arondekar
    Rohit Arondekar
    • State changed from new to stale
    • Importance changed from to

    Marking ticket as stale. If this is still an issue please leave a comment with suggested changes, creating a patch with tests, rebasing an existing patch or just confirming the issue on a latest release or master/branches.

    October 9th, 2010 @ 04:17 AM

  3. bingbing