我想通过rails4-autocomplete实现自动完成
Rails 4.2.4
这是控制器
app/controllers/samples_controller.rb
class SamplesController < ApplicationController
autocomplete :patient, :code
这是路线文件,
config/routes.rb
resources :samples do
get :autocomplete_patient_code, on: :collection
end
这就是观点 应用程序/视图/样品/ _form.html.erb
<div class="field">
<%= f.label :patient_code %><br>
<%= f.autocomplete_field :patient_id, autocomplete_patient_code_samples_path %>
</div>
但是,在尝试保存样本时,我得到了无效的foregin密钥错误,因为患者的代码被传递给foregin密钥而不是ID。我该如何解决这个问题?
这是请求参数:
{"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"}]
答案 0 :(得分:2)
在阅读rails4-autocomplete
的GitHub文档后,我设计了以下解决方案:
将attr_accessor :patient_name
添加到您的Sample
模型,然后按以下方式修改表单:
...
<%= f.autocomplete_field :patient_name, autocomplete_patient_code_samples_path, id_element: '#patient_id' %>
<%= f.hidden_field :patient_id, id: 'patient_id' %>
...
只要您选择任何患者姓名进行此更改,该患者的ID将在隐藏字段中更新,并将作为patient_id提交。
希望这能解决你的问题。
来源:Github