我希望我的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