I want the attributes of my UserPrice model to be 0 by default if they are empty or if it does not check the number. These attributes are tax_rate, shipping_cost and price.
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
At first I put :default => 0inside the table for all 3 columns, but I didn’t want this because it already had filled fields, and I want to use placeholders. Here is my UserPrice model:
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
source
share