【问题标题】:Remove attributes in Mongoid before_save loop删除 Mongoid before_save 循环中的属性
【发布时间】:2012-10-10 17:01:04
【问题描述】:

我认为与其在父文档和嵌入文档中保留 nil/null 中的某些属性(例如,如果不存在价格,则为订单总数),我最好根本不保存它们。如何在保存之前删除 nil 的属性?

# 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

【问题讨论】:

    标签: ruby-on-rails mongoid


    【解决方案1】:

    为什么要从模型中删除属性?在这种情况下,我将添加另一个名为 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
    

    【讨论】:

    • 这是计算总数的好方法。我不想保存为零的属性。例如,有人订购了一件没有价格的商品,那么总数将为 nil/null。我认为我不会保存属性,而不是总共保存 nil/null。对于父文档,似乎我实际上无法保存 nil/null 值(带有 nil 的属性不会被保存),但对于嵌入式文档,Mongoid 确实将它们保存为“null”。我认为最好的办法是拥有一致的数据。
    【解决方案2】:

    Mongoid 支持#unset,所以你可以这样使用:

    order_item.unset(:total)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-01-23
      • 2014-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多