I’m writing a rails app where there is a model that takes certain measures (height, weight, neck_circumference, etc.)
I want it to work both for metric and imperial measurement system.
My model has a measure_unit attribute that can be both metric or imperial. All the measures will be stored in the database in metric system.
I use the simple_form gem, and I have no clue on how to implement the views so that if a user uses the imperial system his data is converted on the fly.
<% if @customer.measure_unit.eql? "metric" %>
<%= f.input :height %></br>
<% else %>
...
<% end %>
How do I fill the blanks?
EDIT — Found a working solution
I ended up using virtual attributes such as “height_in_cm” and “height_in_in” leaving the entries in the database to be stored in mm.
Here is the code for the model:
def height_in_cm
height / 10
end
def height_in_cm=(height)
self.height = height.to_f * 10
end
def height_in_in
height * 0.039370
end
def height_in_in=(height)
self.height = height.to_f / 0.039370
end
And the code for the view:
<% if @customer.measure_unit.eql? "imperial" %>
<%= f.input :height_in_in %></br>
<% else %>
<% if @customer.measure_unit.eql? "metric" %>
<%= f.input :height_in_cm %></br>
<% end %>
<% end %>
One solution would be to pass a hidden field back to the controller indicating that the value passed is imperial and needs to be converted into metric for database storage.
So rather than having a different input for metric and imperial measurements you can simply use a single input which defaults to metric and you have to detect for the non-default (imperial):
Now in your controller action before you have the measurement attribute saved: