Overloading the ActiveRecord Setter

Sometimes, you want to do some extra work when you set an attribute on your ActiveRecord model instance.

You can’t just do this, because you’ll just end up recursively calling the very setter that you’re defining:

class Square < ActiveRecord::Base
    def side=(value)
        self.area = value*value
        self.side = value
    end
end
&#91;/sourcecode&#93;
<div>...and you can't do this because you'll end up modifying a copy of the attributes hash of the model instance, which will not be written through to the database when the model instance is saved ( check out ActiveRecord::Base::attributes in active_record/base.rb):</div>

class Square &gt; ActiveRecord::Base
    def side=(value)
        self.attributes['side'] = value
        self.area = value * value
    end 
end
After looking through the source for ActiveRecord::Base and some testing, I’ve found a method that’s worked for me and appears to be the preferred way of doing it:
class Square &gt; ActiveRecord::Base
    def side=(value)
        self.area = value * value # This would still work because we're calling the default setter for area
        write_attribute('side', value)
    end
end
Alternatively, you could do “self[‘side’] = value” instead of write_attribute.   The index assignment operatore actually does the same thing.
Advertisements

January 13, 2009. Tags: . Uncategorized. Leave a comment.

19 Rails Tricks

I came across this article on Ruby Inside. It contains a nice quick list of things that you might not have known that you can do in Rails.  I find the Rails Engines to be particularly interesting.

http://www.rubyinside.com/19-rails-tricks-most-rails-coders-dont-know-131.html

  1. Benchmark logic in your controller actions
  2. acts_as_nested_set
  3. Easier collections with to_proc
  4. Convert arrays to sentences in views
  5. Send files back to the user
  6. Iterating through page elements with RJS
  7. Check for existence
  8. Number helpers for common number tasks
  9. Testing different route configurations easily
  10. Get lots of info about requests
  11. Improving session performance even more than with ActiveRecord
  12. Caching unchanging data at application startup
  13. Check your views are rendering valid HTML / XHTML
  14. Cleaner HTML output testing 
  15. Run long-running tasks separately in the background
  16. Make ids in URLs more user friendly
  17. Separate out slices of functionality into Engines
  18. Calculations
  19. XML or YAML output of your data 

November 18, 2008. Tags: . Uncategorized. Leave a comment.