Search code examples
ruby-on-railsattrupdate-attributesattr-accessor

Rails 2. Calling virtual attribute's setter by update_attributes


I have one extra attribute in my form (:pagesize) which is not in database. There is also a setter for it:

def pagesize= pagesize
  self.preferences["pagesize"] = pagesize
end

I want 'update_attributes' method to call that setter. What is the best type for :pagesize attribute? attr_accessor, attr_writer...


Solution

  • If that attribute is not defined in your model, you can just define the setter, and then do whichever logic you want:

    class YourModel < ActiveRecord::Base
    
      attr_writer :pagesize
    
      def pagesize=(val)
        self.size_of_page = val
      end
    
    end
    

    something like this. I wrote the AR version because I assumed you are using it, but the principle is the same for DataMapper or mongoid.