Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 如何在数据库中获取BigDecimal值并使其在视图中可读_Ruby_Ruby On Rails 4_Bigdecimal - Fatal编程技术网

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

Ruby 如何在数据库中获取BigDecimal值并使其在视图中可读,ruby,ruby-on-rails-4,bigdecimal,Ruby,Ruby On Rails 4,Bigdecimal,我想展示产品的价格,并了解到使用十进制比使用整数或浮点更可靠 我想知道当实际数字17.99存储为时如何从数据库中提取。如果唯一的问题是复选框列表中显示为的图像价格,只需在ImagePrice模型中定义一个to_s方法,并让它返回价格的字符串表示。例如,如果该价格的十进制值存储在price属性中,则您的方法如下 class ImagePrice < ActiveRecord::Base # ... def to_s price.to_s end end class Im

我想展示产品的价格,并了解到使用十进制比使用整数或浮点更可靠


我想知道当实际数字17.99存储为
时如何从数据库中提取。如果唯一的问题是复选框列表中显示为
的图像价格,只需在
ImagePrice
模型中定义一个
to_s
方法,并让它返回价格的字符串表示。例如,如果该价格的十进制值存储在
price
属性中,则您的方法如下

class ImagePrice < ActiveRecord::Base
  # ...
  def to_s
    price.to_s
  end
end
class ImagePrice
ok,这似乎是有史以来最简单的解决方案:-),非常感谢。但问题是,当我在表单中不使用
to\u s
时,如何调用
to\u s
to\u s
在模型实例上通常由
simple\u form
formtastic
为集合中的每个元素生成标签。如果你好奇的话,你可以查看这些宝石的源代码
simple_form
甚至有一个on选项来指定生成表单标签的方法。谢谢,这非常有帮助,你知道为什么要呈现
吗?Ruby在将值插入字符串或附加到字符串时会自动使用它。如果你在一个对象上调用
to_s
,而该对象没有提供自己的
to_s
方法,默认的返回结果是对象类,后跟它的id。看到三个小时了吗?请阅读。请不要问重复的问题。改为“和”。重复的回答会稀释那些回答问题的人的努力,当他们的工作似乎没有帮助时,会让他们感到沮丧。这也会让搜索者感到困惑。@theTinMan您的评论被采纳了,他会把它放在一个糟糕的日子里,下次我会更努力地自己解决,尽管我仍然不明白为什么会返回
,也许您可以帮帮忙?这个问题在您选择的答案中得到了回答。您必须提供一个
to_s
方法,以有意义/适当的方式输出值。Ruby不知道您想要看到什么,所以它默认为
inspect
类型的输出。
#<IMAGEPRICE:0X007F0431BB0850>
#<IMAGEPRICE:0X007F0431BB0710>
#<IMAGEPRICE:0X007F0431BB05D0>
#<IMAGEPRICE:0X007F0431BB0490>
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
class ImagePrice < ActiveRecord::Base
  # ...
  def to_s
    price.to_s
  end
end