加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 如果空白或未验证数值,则使属性默认为0

发布时间:2020-12-17 03:35:32 所属栏目:百科 来源:网络整理
导读:我希望我的UserPrice模型的属性默认为0,如果它们是空的或者它没有验证数字.这些属性是tax_rate,shipping_cost和price. class CreateUserPrices ActiveRecord::Migration def self.up create_table :user_prices do |t| t.decimal :price,:precision = 8,:sca
我希望我的UserPrice模型的属性默认为0,如果它们是空的或者它没有验证数字.这些属性是tax_rate,shipping_cost和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,:scale => 2
      t.decimal :shipping_cost,:scale => 2
    end
  end
end

起初,我把:default =>所有3列的表内部为0,但我不想这样,因为它已经填写了字段,我想使用占位符.这是我的UserPrice模型:

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

回答

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

解决方法

在这种情况下,我可能会设置:default => 0,:nil => db迁移中为false.

class CreateUserPrices < ActiveRecord::Migration
  def self.up
    create_table :user_prices do |t|
      t.decimal :price,:scale => 2,:default => 0,:nil => false
      t.decimal :tax_rate,:nil => false
      t.decimal :shipping_cost,: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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读