如何在数据库中获取 BigDecimal 值并使其在视图中可读
How to take BigDecimal value in database and make it human readable in view
我想显示产品价格,并且了解到使用 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
我现在被困住了,已经尝试了 3 个小时,但无济于事。
如果唯一的问题是图像价格在复选框列表中显示为 #<IMAGEPRICE:0X007F0431BB0850>
,只需在 ImagePrice
模型中定义一个 to_s
方法并将其设置为 return 价格的字符串表示。例如,如果该价格的十进制值存储在 price
属性中,您的方法将类似于
class ImagePrice < ActiveRecord::Base
# ...
def to_s
price.to_s
end
end
我想显示产品价格,并且了解到使用 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
我现在被困住了,已经尝试了 3 个小时,但无济于事。
如果唯一的问题是图像价格在复选框列表中显示为 #<IMAGEPRICE:0X007F0431BB0850>
,只需在 ImagePrice
模型中定义一个 to_s
方法并将其设置为 return 价格的字符串表示。例如,如果该价格的十进制值存储在 price
属性中,您的方法将类似于
class ImagePrice < ActiveRecord::Base
# ...
def to_s
price.to_s
end
end