0
我有這個類ProfitLoss
其中包含這些字段。我想打電話before_validation
爲before_save
不工作,我想做的事是分配0到那些空白,是Integer
從表單來的值時,這種方法zero_if_blank
。 我搜索了很多像Mysql columns_hash
,但沒有找到任何方法來給予mongo中的每個字段的類型。Mongoid Rails - 有沒有辦法在保存之前檢查字段的數據類型?
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
你試過'場:other_incomes,類型:整數,默認:0'? –
@SergioTulentsev我已經使用過,但在表單輸入上,它顯示所有整數字段爲0,所以我不想使用它。 – Rishabh
您應該能夠在@SergioTulentsev指出的字段上設置[默認值](https://docs.mongodb.com/mongoid/master/tutorials/mongoid-documents/#defaults)。正如手冊所指出的那樣:「如果沒有提供任何東西,你可以告訴Mongoid中的某個字段總是有一個默認值。如果行爲不同,你應該檢查你的表單以及它返回的值。 –