如何在数据库中获取BigDecimal值并使其在视图中可读



我想显示产品的价格,并了解到使用Decimal比使用Integer或Floats可靠得多。

例如,当实际数字17.99存储为<BigDecimal:646c8b8,'0.2E2',9(18)时,我想知道如何从数据库中提取它。我需要在表格中显示这个值。

到目前为止,我有:

f.input :image_prices, as: :check_boxes

在我看来,这将输出:

#<IMAGEPRICE:0X007F0431BB0850>
#<IMAGEPRICE:0X007F0431BB0710>
#<IMAGEPRICE:0X007F0431BB05D0>
#<IMAGEPRICE:0X007F0431BB0490>

但在保存时,会存储正确的ID。模型关系如下:

class Image < ActiveRecord::Base
  has_many :image_options, dependent: :destroy
  has_many :image_prices, through: :image_options
end
class ImageOption < ActiveRecord::Base
  belongs_to :image_price
  belongs_to :image
end
class ImagePrice < ActiveRecord::Base
  has_many :image_options
  has_many :images, through: :image_options
end

我现在太困了,已经试了三个小时了,但都无济于事。

如果唯一的问题是图像价格在复选框列表中显示为#<IMAGEPRICE:0X007F0431BB0850>,只需在ImagePrice模型中定义一个to_s方法,并让它返回价格的字符串表示。例如,如果该价格的十进制值存储在price属性中,则您的方法看起来像

class ImagePrice < ActiveRecord::Base
  # ...
  def to_s
    price.to_s
  end
end

最新更新