rails4-autocomplete with belongs to association

2019-09-09 12:36发布

I want to implement autocomplete via rails4-autocomplete

Rails 4.2.4

Here is the controller

app/controllers/samples_controller.rb

class SamplesController < ApplicationController
autocomplete :patient, :code 

Here is the route file,

config/routes.rb 
resources :samples do
  get :autocomplete_patient_code, on: :collection
end

And that's the view app/views/samples/_form.html.erb

<div class="field">

<%= f.label :patient_code %><br>
<%= f.autocomplete_field :patient_id, autocomplete_patient_code_samples_path %>

</div>

With this code I mange to get the autocomplete autocomplete feature for sample form

However I get invalid foregin key error when try to save the sample that's because the patient's code is passed to the foregin key instead of ID. How do I fix this?

Here is the request Parameters:

{"utf8"=>"✓",
 "authenticity_token"=>"blabla",
 "sample"=>{"patient_id"=>"A123",
 "commit"=>"Create Sample"} 


Get "/samples/autocomplete_patient_code?term=A12" returns 
{"id":"15","label":"A123","value":"A123"}]

1条回答
萌系小妹纸
2楼-- · 2019-09-09 12:56

After reading the GitHub documentation of rails4-autocomplete, I devised the following solution:

Add attr_accessor :patient_name to your Sample model and modify the form as follows:

...
<%= f.autocomplete_field :patient_name, autocomplete_patient_code_samples_path, id_element: '#patient_id' %>
<%= f.hidden_field :patient_id, id: 'patient_id' %>
...

With this change whenever you select any patient name, that patient's ID will be updated on the hidden field and it will be submitted as patient_id.

Hope this solves your problem.

Source: Github

查看更多
登录 后发表回答