ruby on rails - setting activerecord attribute based on virtual attributes -
i have attribute called dimensions
want set based on width
, height
, , depth
attributes.
for example, want shippingprofile.find(1).width = 4
, , have save dimensions {:width => 4, :height => 0, :depth => 0}`
is possible?
class shippingprofile < activerecord::base after_initialize :set_default_dimensions serialize :dimensions, hash attr_accessor :width, :height, :depth attr_accessible :width, :height, :depth, :dimensions private def set_default_dimensions self.dimensions ||= {:width => 0, :height => 0, :depth => 0} end end
very so, need use callback set value of self.dimensions:
class shippingprofile < activerecord::base after_initialize :set_default_dimensions after_validation :set_dimensions serialize :dimensions, hash attr_accessor :width, :height, :depth attr_accessible :width, :height, :depth, :dimensions private def set_default_dimensions self.dimensions ||= {:width => 0, :height => 0, :depth => 0} end def set_dimensions self.dimensions = { :width => self.width || self.dimensions[:width], :height => self.height || self.dimensions[:height], :depth => self.depth || self.dimensions[:depth], } end end
you need use self.foo || self.dimensions[:foo]
ensure preserve existing values set in hash. why? dimension attributes (i'm assuming) aren't being persisted in database - you're using attr_accessor, rather setting them fields in table.
as aside, think you're going model design wrong way. storing dimensions hash in database, not lose ability query based on attributes, add level of fragility don't need.
if are storing individual dimension attributes separate fields, you're introducing redundancy , complexity. better served having 3 attributes fields in database (if aren't already), generating dimensions hash on fly when it's needed:
class shippingprofile < activerecord::base def dimensions { :width => self.width, :height => self.height, :depth => self.depth } end end
this way, retain functionality , gain flexibility.
Comments
Post a Comment