-->

autocomplete field is empty when editing form

2019-09-05 19:18发布

问题:

I have a sample model in which belongs_to a patient model.Using rails-jquery-autocomplete I have managed to implement an autocomplete field where one can search patient's code and it works well. However when editing the form, the patient code is empty on the form. How should I fix it?

App/views/sample/_form.html.erb

    <div class="field">
       <%= f.label :patient_code %><br>
       <%= f.hidden_field :patient_id, id: 'patient_id' %>
       <%= f.autocomplete_field :patient_code, autocomplete_patient_code_samples_path, id_element: '#patient_id' %>
    </div>

回答1:

I faced the same issue while editing the saved model, a quick workaround would be as follows:

...
<%= f.autocomplete_field :patient_code, autocomplete_patient_code_samples_path, id_element: '#patient_id', value: (!@sample.new_record?)? @sample.patient.code : '' %>
...

Assuming that the instance variable is @sample. Modify it according to your scenario. Cheers!