Setting the activerecord attribute based on virtual attributes

I have an attribute dimensionsthat I want to set based on attributes width, heightand depth.

for example, I want to make ShippingProfile.find(1).width = 4and save it in sizes as {: width => 4 ,: height => 0 ,: depth => 0} `

Is it 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
+3
source share
3 answers

Very important, all you have to do is use the callback to set the 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

self.foo || self.dimensions[:foo], , . ? ( ) - attr_accessor, .

, , . , , , .

, . ( ), , :

class ShippingProfile < ActiveRecord::Base
  def dimensions
    { :width => self.width, :height => self.height, :depth => self.depth }
  end
end

, .

+7
ShippingProfile.find(1).dimensions[:width] = 4
0

You can use the class in serialization, therefore

class ShippingProfile < ActiveRecord::Base
  serialize :dimensions, Dimensions
end

class Dimensions
  attr_accessor :width, :height,:depth

  def initialize
    @width = 0
    @height = 0
    @depth = 0
  end

  def volume
    width * height * depth
  end
end

Now you can do ShippingProfile.dimensions.width = 1 and later ShippingProfile.dimension.volume, etc.

Model will be richer in presentation than hash

0
source

Source: https://habr.com/ru/post/1791113/


All Articles