ruby-on-railsrubyruby-on-rails-4simple-form

Ruby on Rails - form input a column and insert another column in the form


There is a question about simple_form in Ruby on Rails.
I would like to create a form.

I have two model like: Vehicle, Repair.

 <%= simple_form_for(@repair) do |f| %>
   <div class="form-inputs">
     <%= f.input :vehicle_id, include_blank: true, label: 'Vehicle_no' %>
   </div>
 <% end %>

When I create the repair form, I would like to search @vehicle.no.
and When I key in the keyword about vehicle number like: XXX-1211 and I choose the one I need, then I could get the id with @vehicle.no to placing with the vehicle number.

How could I achieve with that?

Thank you!

> Updated

I have a input area to search for the Vehicle Number, but that value would be Vehicle id.

Form => Vehicle No [_____] <= input the vehicle.no, but I would like to put the value about the vehicle's id.

> Updated

This is the form This is the form above.

enter image description here And when I key in the part of the vehicle number, it could appear some vehicle number to be choosen.(Search Part)
enter image description here
If I choose XXX-112, and according to the below datatables, I could get the value id = 2 to submit the form.

  1. Vehicle_tables
id no
1 XXX-111
2 XXX-112
3 XXX-332
.
.
.
100 XXX-222

How could I achieve this goal? It use some of AJAX function?

I would like to use the search method because I have many vehicles data...

Sorry about the English skill to clearify the question..... :-(


Solution

  • https://github.com/plataformatec/simple_form#associations

    <%= f.association :vehicle, label_method: :no, value_method: :id %>

    This of course assumes that Repair has a has_one :vehicle line in its model file.

    What this code will do is generate a select tag with all of the labels equal to the :no (which I assume is of the format XXX-1211), but the value of the select elements will be the vehicle_id

    Now if you create a new repair, it will be a dropdown showing the @vechicle.no but storing @vechicle.id in the database.

    To be able to search, you'll need some extra javascript library like select2 that turns a select box into an autocomplete element. Then you add input_html: {class: "select2"} to the f.input line above to use it.