0

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...

Piotr Brudny
  • 654
  • 4
  • 16

2 Answers2

1

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.

ChuckE
  • 5,610
  • 4
  • 31
  • 59
  • By the way, I think you can do without attr_writer, provided you don't want to store the value. attr_writer provides you in this case an instance var @pagesize. You can use it only internally and cannot access it from the outside. But this is only worth if you really need the variable. Otherwise the setter method will suffice. – ChuckE Oct 09 '12 at 07:18
1

u can call update_attributes on a attr_accessor variable but it needs to be defined as accessible. Also, if u define the variable as attr_writer, u dont need to define a setter method since its added in the backend. Checkout Why use Ruby's attr_accessor, attr_reader and attr_writer? for more info

Community
  • 1
  • 1
Prasad Surase
  • 6,486
  • 6
  • 39
  • 58