我在Auto-complete Associations上关注了Railscast,但我被困在自动完成的一半。我没有使用Prototype而是使用Jquery而且我不知道如何让自动完成一半工作。怎么做?
与Railscast相比,这是自定义:
产品型号:
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
上面提供了一个虚拟属性,我在其中为我的产品表单:business_name
将我的位置模型location_name
定义为<%= f.text_field :location_name %>
,因为产品属于某个位置。
编辑:这是使用Jquery Autocomplete Gem,但我愿意接受替代方案。
我的产品:name
很有魅力;
<%= f.autocomplete_field :name, autocomplete_product_name_products_path %>
但是,如果我为:location_name
添加这样的东西,那就不行了;
<%= f.autocomplete_field :location_name, autocomplete_product_location_name_products_path %>
答案 0 :(得分:3)
很简单,不得不添加attr_accessor
,这是我从另一个项目中完成的代码:
<%= 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
确保在应用程序布局中指定所需的文件,或者由于某些奇怪的原因它无法正常工作(rails 3.0.9)
<%= javascript_include_tag "autocomplete-rails", "jquery-ui-1.8.16.custom.min" %>
答案 1 :(得分:1)
我不确定,但您是否尝试过使用autocomplete_location_location_name_products_path
?
答案 2 :(得分:0)
由于我无法为Jquery-Autocomplete使用自动完成功能,我刚刚开始使用Jquery-TokenInput插件进行我的位置,只是将限制设置为1个令牌,我从{{3}中学到了很多东西也是。