ruby-on-railsrubymongodbmongoidbefore-save

Mongoid Rails - Is there a way to check the field's datatype before saving?


I have this class ProfitLoss which consists of these fields. I want to call this method zero_if_blank on before_validation as before_save is not working and what i want to do is assign 0 to those values which are blank and are of Integer when coming from the form. I searched a lot like the Mysql columns_hash but didn't find any method to give the type of each field in mongo.

class ProfitLoss < Generic
  include Mongoid::Document
  include Mongoid::Timestamps
  include MongoMysqlRelations

  field :fiscal_year, type: String
  field :sales_excluding_other_incomes, type: Integer
  field :other_incomes, type: Integer
  field :closing_stock, type: Integer

  before_validation :zero_if_blank

  def zero_if_blank
    pp self.columns_hash.each {|k,v| puts "#{k} => #{v.type}"}
  end
end

Solution

  • this piece of code did the work :)

    def zero_if_blank 
      self.fields.each do |k,v|
       if v.type == Integer && self.attributes[k] == nil
         self.__send__("#{k}=", 0)
       end
      end
    end