Ruby on rails 在保存循环之前删除Mongoid中的属性
我认为,与其在父文档和嵌入文档中保留某些属性为零/空(例如,如果不存在价格,则订单总数),我最好根本不保存它们。如何在保存之前删除为零的属性Ruby on rails 在保存循环之前删除Mongoid中的属性,ruby-on-rails,mongoid,Ruby On Rails,Mongoid,我认为,与其在父文档和嵌入文档中保留某些属性为零/空(例如,如果不存在价格,则订单总数),我最好根本不保存它们。如何在保存之前删除为零的属性 # embedded order position for each order class Orderitem include Mongoid::Document field :quantity, :type => Integer field :unit_price, :type => Integer field :tota
# embedded order position for each order
class Orderitem
include Mongoid::Document
field :quantity, :type => Integer
field :unit_price, :type => Integer
field :total, :type => Integer
field :economical_potential, :type => Integer
embedded_in :order
belongs_to :supplier
belongs_to :item
before_save :remove_empty_fields
private
def remove_empty_fields
attributes.each do |attr_name, value|
if value.nil?
# don't save attribute
end
end
end
end
为什么要从模型中删除属性?在这种情况下,我将添加另一个名为unit的模型,并添加:price作为属性。然后向Orderitem添加一个名为def total_of_unit的函数,该函数将根据单位数量及其价格返回总数 在代码中,它将如下所示:
class Orderitem
...
field :quantity, :type => Integer
# drop :unit_price
# drop :total
field :economical_potential, :type => Integer
...
has_many :units
...
def total
@total = 0
self.units.each do |unit|
@total = @total + unit.price
end
return @total
end
end
class Unit
field :unit_price, :type => Integer
belongs_to :Orderitem
end
order_item.unset(:total)
单元将如下所示:
class Orderitem
...
field :quantity, :type => Integer
# drop :unit_price
# drop :total
field :economical_potential, :type => Integer
...
has_many :units
...
def total
@total = 0
self.units.each do |unit|
@total = @total + unit.price
end
return @total
end
end
class Unit
field :unit_price, :type => Integer
belongs_to :Orderitem
end
order_item.unset(:total)
Mongoid支持unset,因此您可以使用如下内容:
class Orderitem
...
field :quantity, :type => Integer
# drop :unit_price
# drop :total
field :economical_potential, :type => Integer
...
has_many :units
...
def total
@total = 0
self.units.each do |unit|
@total = @total + unit.price
end
return @total
end
end
class Unit
field :unit_price, :type => Integer
belongs_to :Orderitem
end
order_item.unset(:total)
这是计算总数的好方法。我不想保存为零的属性。例如,有人订购了一个没有价格的商品,其总额将为零/空。我认为我不会保存该属性,而不是总共保存nil/null。对于父文档,似乎我实际上无法使用nil保存nil/null值属性,但对于嵌入式文档,Mongoid使用null保存属性。我认为最好是有一致的数据。