使用 'step' 接受表格中的小数:小数未正确保存在数据库中
Accept decimals in form using 'step': decimal is not saving correctly in database
我试图在我的表单中接受小数:
<%= f.label :price %><br />
<%= f.number_field :price, :step => 0.01 %>
但只要我在客户端的表单中输入 13.75 之类的数字,它就会将该数字四舍五入为 13.00 美元。这是显示价格的代码:
<%= number_to_currency(@product.price) %>
我不认为 number_to_currency 方法与它有任何关系,但我想它值得注意。
非常感谢任何帮助,谢谢!
在你的 schema.rb 文件中你应该有
t.float "price"
而不是
t.integer "price"
或
t.string "price"
为此,运行 rails g migration change_data_type_for_fieldname
现在新的迁移文件应该出现在 db/migrate:
class ChangeDataTypeForFieldName < ActiveRecord::Migration
def up
end
def down
end
end
填写专有名称:
class ChangeDataTypeForFieldName < ActiveRecord::Migration
def self.up
change_table :table_name do |t|
t.change :field , :new_datatype
end
end
def self.down
change_table :table_name do |t|
t.change :field, :old_data_type
end
end
end
运行 rake db:migrate
我试图在我的表单中接受小数:
<%= f.label :price %><br />
<%= f.number_field :price, :step => 0.01 %>
但只要我在客户端的表单中输入 13.75 之类的数字,它就会将该数字四舍五入为 13.00 美元。这是显示价格的代码:
<%= number_to_currency(@product.price) %>
我不认为 number_to_currency 方法与它有任何关系,但我想它值得注意。
非常感谢任何帮助,谢谢!
在你的 schema.rb 文件中你应该有
t.float "price"
而不是
t.integer "price"
或
t.string "price"
为此,运行 rails g migration change_data_type_for_fieldname
现在新的迁移文件应该出现在 db/migrate:
class ChangeDataTypeForFieldName < ActiveRecord::Migration
def up
end
def down
end
end
填写专有名称:
class ChangeDataTypeForFieldName < ActiveRecord::Migration
def self.up
change_table :table_name do |t|
t.change :field , :new_datatype
end
end
def self.down
change_table :table_name do |t|
t.change :field, :old_data_type
end
end
end
运行 rake db:migrate