0

Suppose I have three models:

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

and while editing the details for an Event I want to add contacts for that event. I use an autocomplete field but I only want the autocomplete list to show Contacts from the city the Event is happening in; i.e. If an event is happening in New York I only want to see contacts from New York and no where else.

Is this possible with rails4-autocomplete? Any suggestions?

Colin Wu
  • 611
  • 7
  • 25

1 Answers1

0

Found the answer here: Rails gem rails3-jquery-autocomplete how to scope by user

Turns out redefining get_autocomplete_items is the ticket so, for my specific example, my EventsController would have:

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

and the view would have

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

Hope this helps others.

Community
  • 1
  • 1
Colin Wu
  • 611
  • 7
  • 25