Search code examples
htmlruby-on-railsrubyerb

Dynamically display formatted value in f.text_field without JavaScript


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?


Solution

  • 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)
      self.price = (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.