如何限制 rails4-autocomplete 的数据源

How to limit data source for rails4-autocomplete

假设我有三个模型:

class City < ActiveRecord::Base
  has_many :events
  has_many :contacts
end

class Event < ActiveRecord::Base
  belongs_to :city
  has_many :contacts
end

class Contact < ActiveRecord::Base
  belongs_to :city
end

在编辑活动的详细信息时,我想为该活动添加联系人。我使用自动完成字段,但我只希望自动完成列表显示事件发生城市的联系人;即,如果在纽约发生事件,我只想查看来自纽约的联系人,而不是其他任何地方。

rails4-autocomplete 可以吗?有什么建议吗?

在这里找到答案:Rails gem rails3-jquery-autocomplete how to scope by user

原来重新定义 get_autocomplete_items 是门票所以,对于我的具体示例,我的 EventsController 将具有:

class EventsController < ApplicationController
  autocomplete :contact, name, full: true
  ...
  def get_autocomplete_items(parameters)
    super(parameters).joins(:city).where(["cities.name = ?", params[:city]])
  end
end

并且视图将具有

<%= autocomplete_field_tag :contact_name, '', autocomplete_contact_name_events_path(:city => @event.city.name) %>

希望这对其他人有帮助。