In the database, prices are stored in cents, and it’s easy to display them in the proper format, but when I try to use the text_field
helper, there doesn’t appear to be a way to format the money in the input’s value without Javascript.
<%= form_with model: @item, local: true do |f| %>
...
<div class="flex flex-col mb-3">
<%= f.label :price, 'Price' %>
<%= f.text_field :price, type:'number' %>
</div>
...
<% end %>
Are there any ways to do this in plain HTML/Ruby, and if not, are there any simple JavaScript workarounds using the built-in Stimulus library?
2
Answers
Instead of
text_field
, try usingnumber_field_tag
with a step attribute specified.I would do that by not exposing the original, cent-based value in the form, but by using a custom dollar-based attribute.
and use that attribute in the form like this:
Note: You will need to add
price_in_dollars
to the strong parameters in your controller too.