I followed the Railscast on Auto-complete Associations but i am stuck at the autocomplete half. I am not using Prototype but Jquery instead and i don't know how to get the autocomplete half working. How is it done?
This is the customization compared to what the Railscast has:
Products Model:
def location_name
location.business_name if location
end
def location_name=(business_name)
self.location = Location.find_by_business_name(business_name) unless business_name.blank?
end
The above makes a virtual attribute in which i defined my Location models :business_name
into location_name
for the <%= f.text_field :location_name %>
of my products form because a product belongs to a Location.
EDIT: This was using the Jquery Autocomplete Gem but i am open to alternatives.
My product :name
works a charm;
<%= f.autocomplete_field :name, autocomplete_product_name_products_path %>
But if i put something like this for :location_name
its no g开发者_如何学运维ood;
<%= f.autocomplete_field :location_name, autocomplete_product_location_name_products_path %>
It was simple, had to add attr_accessor
, this is my finished code from another project:
<%= form_for(@business_address) do |f| %>
<%= f.error_messages %>
<%= f.label :name, "Address" %><br />
<%= f.autocomplete_field :name, autocomplete_business_address_name_business_addresses_path %>
<%= f.label :business_name, "Business" %>
<%= f.autocomplete_field :business_name, autocomplete_business_name_business_addresses_path %>
<%= f.submit %>
<% end %
class BusinessAddress < ActiveRecord::Base
attr_accessible :name, :business_name
belongs_to :business
attr_accessor :business_name
def business_name
business.name if business
end
def business_name=(name)
self.business = Business.find_or_create_by_name(name) unless name.blank?
end
end
class BusinessAddressesController
autocomplete :business, :name, :full => true
autocomplete :business_address, :name, :full => true
end
Routes.rb
resources :business_addresses do
get :autocomplete_business_name, :on => :collection
get :autocomplete_business_address_name, :on => :collection
end
Make sure you specify in your application layout the files needed or for some strange reason it won't work (rails 3.0.9)
<%= javascript_include_tag "autocomplete-rails", "jquery-ui-1.8.16.custom.min" %>
I am not sure, but have you tried using autocomplete_location_location_name_products_path
?
Since i couldn't get the Autocomplete working for the Jquery-Autocomplete i just started using Jquery-TokenInput plugin for my locations and just set the Limit to 1 Token only, i learned a lot from the Railscasts too.
精彩评论