简体   繁体   中英

How do I handle person height within a simple_form?

I have a Profile model, that has a height attribute.

I need to store the height of users (aka profiles), but I am not quite sure how to do it. I assume the best way to do it is to have a select dropdown broken down in inches (ie 4'0", 4'1"...6'5", etc.). But I am not quite sure the best way to store this in the db.

I would assume it is simplest to just store inches, but if I do how do I present the height in my select in the format I specified above.

Right now, I just have an integer field:

<%= f.input_field :height, placeholder: "176", class: 'col-lg-9 form-control' %>

You can use a number field for this. When saving the users height or updating a user height you can provide an option for the user either choosing it in inches or cms . You can either use javascript or jquery to convert to appropriate units before saving or you can use a before filter for updating and creating operations.

You can do the following instead of text_field and you can even set min and max values for height.

<%= f.number_field :height, placeholder: "176", class: 'col-lg-9 form-control' %>

1.Change hieght variable data type to float as centimeters.

2.Display drop down of foot and inches and convert it into centimeters before save and viceversa before display stored data.

in your view:

<select name=profile[height]>height
<option>4.1</option>
<option>4.2</option>
<option>4.3</option>
<option>4.4</option>
</select>

in your create action of controller:

@profile = Profile.new(profile_params)
@profile.height = @profile.height*30.48 #convert foot to centimeters
@profile.save

You can create select box with value and option to select.

For example: value in database will be 4.4 , but option in select will be 4'4

 <% arr = (1..10).step(0.1).to_a.map{|k| k.round(1).to_s.sub(".", "'"), [k.round(1) ]  } %>

 <%= f.select :height, arr, placeholder: "176", class: 'col-lg-9 form-control' %>

(1..10) is your scope ,you can put here range whatever you want.

Here is an example code snippet that shows one way that this could look. If you add the inches integer value to the select option tags, you could then grab it using jQuery upon a save operation.

 $(document).ready(function() { $('#save').on('click', function(){ alert($('#height').val()); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id='height'> <option value="72">6'0"</option> <option value="73">6'1"</option> <option value="74">6'2"</option> <option value="75">6'3"</option> <option value="76">6'4"</option> </select> <input type="button" id="save" value="Save" /> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM