2012-01-17 34 views
5

Tôi muốn các thuộc tính của mô hình UserPrice của tôi mặc định là 0 nếu chúng trống hoặc nếu nó không hợp lệ hóa số. Các thuộc tính này là tax_rate, shipping_cost và giá.Đặt thuộc tính mặc định là 0 nếu để trống hoặc nếu không xác thực số

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 

Lúc đầu, tôi đặt :default => 0 bên trong của bảng cho tất cả 3 cột nhưng tôi không muốn điều đó bởi vì nó đã có những lĩnh vực điền vào và tôi muốn sử dụng placeholders. Đây là mô hình UserPrice tôi:

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

ĐÁP

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 

Trả lời

3

Trong trường hợp này tôi có lẽ sẽ thiết lập: mặc định => 0,: nil => sai trong cuộc di cư db.

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 

Tôi sử dụng Trình chỉnh sửa thuộc tính khi thực hiện các công cụ nâng cao hơn như định dạng số điện thoại https://github.com/mdeering/attribute_normalizer. Trình bình thường thuộc tính thực sự tốt để đảm bảo định dạng dữ liệu.

# 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

Bạn có thể có thể chỉ cần đặt nó trong một hành động before_validation vòng đời:

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 

Bạn không cần phải kiểm tra nếu đầu vào là một chuỗi từ Rails sẽ mặc nó để 0 trong kịch bản đó anyways . Nếu bạn chỉ cần xác thực này trong hành động create thì bạn có thể thay đổi thành:

before_validation :default_to_zero_if_necessary, :on => :create 
Các vấn đề liên quan