Set default attributes to 0 if empty or if not checking for a numerical value

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
+5
source share
2 answers

In this case, I would probably set: default => 0 ,: nil => false in the db migration.

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

Normalizer, , 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
+3

, 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
+5

All Articles