Reputation: 63
In my model I have an attribute "duration" (seconds as an integer) But the views new/edit have input for: hours, minutes, seconds.
Should I have in model (attr_accessor :hours, :minutes, :seconds) then how do I convert these virtual attributes into my "duration" attribute, Coming from Java I'd have setter/getter on "duration"!
Upvotes: 2
Views: 1747
Reputation: 2640
You can set a before_save filter to calculate it's value from the values of your virtual accesors (being hours, minutes and seconds). Something like:
class Model << AR:Base
attr_accessor :hours, :minutes, :seconds
before_save :update_duration
def update_duration
duration = = hours*3600 + minutes*60 + secods
end
end
It's a bit rough, but should give you an idea on how it could work. Whenever you call the "save" method on the model (either on a create or update actions), the filter will be called before accesing the BD, update it's value and then proceed to save it properly.
Upvotes: 6