Surely I'm missing something pretty obvious... I have a field that is decimal with precision 2, but Formtastic is displaying it with only a single decimal, unless the actual value has 2 places. What am I missing?
Model:
create_table "items", :force => true do |t|
t.string "item_number"
t.integer "buyer_id"
t.integer "seller_id"
t.string "description"
t.decimal "sales_price", :precision => 10, :scale => 2, :default => 0.0
t.datetime "created_at"
t.datetime "updated_at"
end
View
%td= bought.input :sales_price, input_html: { class: 'span2'}, label: false
Noting answer from below, which might not be clear to others finding this later:
%td= bought.input :sales_price, input_html: { class: 'span2', value: number_with_precision(bought.object.sales_price, precision: 2)}, label: false
Try this:
%td= bought.input :sales_price, input_html: { class: 'span2', value: number_with_precision(bought.sales_price, precision: 2) }, label: false
Sales_price is being stored in your database with two decimal places, but you have to tell rails to format it that way when displaying the value.
@xnm's answer was helpful to me, but doing this on each input would be tedious, so I took it a step further to solve this problem application-wide.
I did this by modifying the behavior of regular input fields, which Formtastic calls StringInput
, by creating my own version, as shown in in the Formtastic README.
The code below is for for DataMapper models, so that anytime a property is declared as Decimal
, the input will show the correct number of decimal places. This approach could be modified for other ORMs.
# app/inputs/string_input.rb
# Modified version of normal Formtastic form inputs.
# When creating an input field for a DataMapper model property, see if it is
# of type Decimal. If so, display the value with the number of decimals
# specified on the model.
class StringInput < Formtastic::Inputs::StringInput
def to_html
dm_property = @object.class.properties.detect do |property|
property.name == @method
end rescue nil
if dm_property && dm_property.class == DataMapper::Property::Decimal
@options[:input_html] ||= {}
@options[:input_html][:value] ||= @template.number_with_precision(
# What DataMapper calls "scale" (number of digits right of the decimal),
# this helper calls "precision"
@object.send(@method), precision: dm_property.options[:scale]
)
end
super
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With