2012-01-17 45 views
5

我希望我的UserPrice模型的屬性默認爲0,如果它們爲空或者如果它不驗證數字性。這些屬性是tax_rate,shipping_cost和price。如果屬性默認爲0,如果爲空或者如果不驗證數字

class CreateUserPrices < ActiveRecord::Migration 
    def self.up 
    create_table :user_prices do |t| 
     t.decimal :price, :precision => 8, :scale => 2 
     t.decimal :tax_rate, :precision => 8, :scale => 2 
     t.decimal :shipping_cost, :precision => 8, :scale => 2 
    end 
    end 
end 

起初,我把:default => 0表內所有3列,但我不想因爲它已經有了填補了領域,我想使用的佔位符。這裏是我的UserPrice型號:

class UserPrice < ActiveRecord::Base 
    attr_accessible :price, :tax_rate, :shipping_cost 
    validates_numericality_of :price, :tax_rate, :shipping_cost 
    validates_presence_of :price 
end 

ANSWER

before_validation :default_to_zero_if_necessary, :on => :create 

private 

def default_to_zero_if_necessary 
    self.price = 0 if self.price.blank? 
    self.tax_rate = 0 if self.tax_rate.blank? 
    self.shipping_cost = 0 if self.shipping_cost.blank? 
end 

回答

3

在這種情況下,我可能會設置:默認=> 0,:在數據庫遷移零=>假的。

class CreateUserPrices < ActiveRecord::Migration 
    def self.up 
    create_table :user_prices do |t| 
     t.decimal :price, :precision => 8, :scale => 2, :default => 0, :nil => false 
     t.decimal :tax_rate, :precision => 8, :scale => 2, :default => 0, :nil => false 
     t.decimal :shipping_cost, :precision => 8, :scale => 2, :default => 0, :nil => false 
    end 
    end 
end 

不得不做更高級的東西,如格式化的電話號碼https://github.com/mdeering/attribute_normalizer當我使用屬性正規化。屬性規範化器對確保數據格式非常有用。

# here I format a phone number to MSISDN format (004670000000) 
normalize_attribute :phone_number do |value| 
    PhoneNumberTools.format(value) 
end 

# use this (can have weird side effects) 
normalize_attribute :price do |value| 
    value.to_i 
end 

# or this. 
normalize_attribute :price do |value| 
    0 if value.blank? 
end 
5

你可能只把它放在一個before_validation生命週期操作:

before_validation :default_to_zero_if_necessary 

private 
    def default_to_zero_if_necessary 
    price = 0 if price.blank? 
    tax_rate = 0 if tax_rate.blank? 
    shipping_cost = 0 if shipping_cost.blank? 
    end 

你並不需要檢查,如果輸入的是一個字符串,因爲Rails會在那種情況下它默認爲0反正。如果您在create操作期間只需要此驗證,則可以將其更改爲:

before_validation :default_to_zero_if_necessary, :on => :create 
相關問題