自动完成多对多轨道4

时间:2015-12-25 17:55:21

标签: ruby-on-rails-4

我有3个模型,有很多关系。我需要用自动完成替换f.select。有人可以帮帮我吗?我还在学习铁轨。

型号:

medic_record.rb

has_many :lab_medics
has_many :labs, :through => :lab_medics

lab.rb

has_many :lab_medics
has_many :medic_records, :through => :lab_medics

lab_medic.rb

belongs_to :medic_record
belongs_to :lab

查看:

medic_records / _form.html.erb

<div class="form-group">
  <%= f.label :lab_ids, 'Lab Test' %>
  <%= f.select :lab_ids, @labs.collect {|x| [x.name, x.id]}, {}, :multiple => true, class: "form-control" %>            
</div>

控制器:

medic_records.rb

def new
  @medic_record = MedicRecord.new
  @labs = Lab.all
end

def create
  @medic_record = MedicRecord.new(medic_record_params)
  @labs = Lab.all
  respond_to do |format|
    if @medic_record.save
      format.html { redirect_to medic_records_path, notice: 'MedicRecord was successfully created.' }
      format.json { render :show, status: :created, location: @medic_record }
      format.js
    else
      format.html { render :new }
      format.json { render json: @medic_record.errors, status: :unprocessable_entity }
    end
  end
end

private

    def medic_record_params
      params.require(:medic_record).permit(:date, :therapy, :lab_ids => [])
    end

1 个答案:

答案 0 :(得分:1)

您可以跳过使用自动填充功能并使用chosen

选上的

选择并保存chosen.jquery.js中的vendor/assets/javascriptschosen.css中的vendor/assets/stylesheets,以及vendor/assets/images中选择的精灵图片。

添加到application.css

# application.css    
=* require chosen

application.js

# application.js
=// require chosen.jquery

$('#medic_records_lab_ids).chosen();

或者如果你坚持使用自动完成功能:

自动填充

您可以使用rails4-autocomplete gem。运行bundle install后,将这些行添加到application.js

//= require jquery-ui
//= require autocomplete-rails

<强>控制器

# medic_records_controller
class MedicRecordsController << ApplicationController
  autocomplete :lab, :name
end

<强>路线

resources :medic_records do
  get :autocomplete_lab_name, on: :collection
end

<强>视图

# _form.html.erb
<div class="form-group">
  <%= f.label :lab_ids, 'Lab Test' %>
  <%= f. autocomplete_field, autocomplete_lab_name_medic_records_path %>            
</div>