Ruby on rails 基于虚拟属性设置activerecord属性
我有一个名为Ruby on rails 基于虚拟属性设置activerecord属性,ruby-on-rails,activerecord,attributes,Ruby On Rails,Activerecord,Attributes,我有一个名为dimensions的属性,我想根据我的宽度、高度和深度属性设置该属性 例如,我想执行ShippingProfile.find(1).width=4,并将其保存为{:width=>4,:height=>0,:depth=>0}的维度` 这可能吗 class ShippingProfile < ActiveRecord::Base after_initialize :set_default_dimensions serialize :dimensions, Hash
dimensions
的属性,我想根据我的宽度
、高度
和深度
属性设置该属性
例如,我想执行ShippingProfile.find(1).width=4
,并将其保存为{:width=>4,:height=>0,:depth=>0}的维度`
这可能吗
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
class ShippingProfile0,:高度=>0,:深度=>0}
结束
结束
非常好,因此,您只需使用回调来设置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
这样,您就保留了功能并获得了一些灵活性。您可以在serialize中使用类,因此
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
class ShippingProfile
现在可以执行ShippingProfile.dimensions.width=1和更高版本的ShippingProfile.dimension.volume等操作
一个模型比一个散列更丰富,你不认为ShippingProfile.find(1).dimensions.width=4更好吗?所以我选择存储单个维度。它的问题要小得多,正如您所说,查询更加灵活。有时我会忙于保持一个漂亮的数据库,但事实是,我从来没有真正看它:)
class ShippingProfile < ActiveRecord::Base
def dimensions
{ :width => self.width, :height => self.height, :depth => self.depth }
end
end
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