skip to Main Content

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


  1. Instead of text_field, try using number_field_tag with a step attribute specified.

    <%= f.number_field_tag :price, nil, step: 0.01 %>
    # => <input id="price" name="price" step="0.01" type="number" />
    
    Login or Signup to reply.
  2. I would do that by not exposing the original, cent-based value in the form, but by using a custom dollar-based attribute.

    # in app/models/item.rb
    def price_in_dollars
      '%.2f' % (price / 100.0)
    end
    
    def price_in_dollars=(string)
      (string.to_f * 100).round
    end
    

    and use that attribute in the form like this:

    <%= form_with model: @item, local: true do |f| %>
      ...
      <div class="flex flex-col mb-3">
        <%= f.label :price, 'Price' %>
        <%= f.text_field :price_in_dollars, type: 'number' %>
      </div>
      ...
    <% end %>
    

    Note: You will need to add price_in_dollars to the strong parameters in your controller too.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search