Rails 2. Calling virtual attribute's setter by update_attributes
-
05-07-2021 - |
سؤال
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...
المحلول
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.
نصائح أخرى
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