Rails应用中能否在Model层配置产品价格自动格式化为$123.99?
解决方法
你用的是money-rails的monetize宏处理价格,完全可以在模型层统一配置格式化逻辑,不用每次在视图里重复写number_to_currency。下面是几种可行方案:
方案一:全局统一货币格式(推荐)
如果希望所有货币字段都采用相同的格式化规则,在项目的config/initializers/money.rb文件里添加全局配置:
MoneyRails.configure do |config| config.default_format = { precision: 2 # 可按需添加其他配置,比如 locale: :zh, symbol: '¥' 等 } end
配置完成后,在视图里直接写<%= product.price %>就会自动输出格式化后的价格(ERB会自动调用对象的to_s方法,money-rails会用你配置的格式生成字符串)。
方案二:模型内定义专属格式化方法
如果只想让Product模型的价格用这个格式,不影响其他模型,直接在Product类里新增一个方法:
class Product < ApplicationRecord monetize :price_cents, numericality: true mount_uploader :image, ProductImageUploader belongs_to :category validates :name, presence: true validates :price, presence: true validates :quantity, presence: true validates :category, presence: true def formatted_price price.format(precision: 2) end end
之后在视图里调用<%= product.formatted_price %>即可,语义更清晰,也不会干扰原始的price对象。
方案三:重写price的to_s方法(谨慎使用)
如果想彻底让product.price在所有输出场景自动格式化,可以在monetize的时候重写to_s方法,但注意这会改变该Money对象的默认字符串表现,确保没有其他场景需要原始数值输出:
class Product < ApplicationRecord monetize :price_cents, numericality: true do def to_s format(precision: 2) end end # 其余代码不变... end
这样在视图里直接写<%= product.price %>就会得到格式化后的结果。
内容的提问来源于stack exchange,提问作者Liam Naylor
相关产品推荐
相关产品推荐

