开发者

Why doesn't this autocomplete field work?

开发者 https://www.devze.com 2023-02-20 06:36 出处:网络
I\'m trying to use this autocomplete field with a set of prepopulated genres. Genre has a has_and_belongs_to_many association with Profile.

I'm trying to use this autocomplete field with a set of prepopulated genres.

Genre has a has_and_belongs_to_many association with Profile.

I have this in my routes:

resources :profiles
resources :genres

This is my genres controller:

respond_to :html, :json

def index
  respond_with(@genres = Genre.search(params[:q]))
end

And this is my Genre model:

has_and_belongs_to_many :videos
has_and_belongs_to_many :profiles

scope :search, lambda {|q| where("name LIKE ?", '%q%') }

This is in my application.js:

$("#genre_field").tokenInput(genres_path);

This is my profile edit view:

<%= f.fields_for :genre do |g| %>
 <div class="field">
      <%= g.label :name, "Genres" %>开发者_StackOverflow中文版;<br />
      <%= g.text_field :name, :id => 'genre_field' %>
  </div>
<% end %>

I've already prepopulated the genres table with a set of genres and I include the jquery.tokeninput.js and CSS files.

So why is the text field not showing the autocomplete results? What am I missing?


Based on your comments I think I've figured out your problem. In your application.js you have the following:

$("#genre_field").tokenInput(genres_path);

which maps the DOM element #genre_field to receive data from genres_path.

genres_path, however, does not exist in the context of your JavaScript file. The method genres_path exists in ruby because rails generates that method via routes.rb, not in JS. In order to fix this you'll need to provide the relative path that genres_path represents in your JS code:

$("#genre_field").tokenInput("/path/to/genres");

or

You need to create some sort of js.erb file that makes use of genres_path:

$("#genre_field").tokenInput(<%= genres_path %>);

or

You can add an inline script to your html.erb file that handles all of this code in a similar fashion to the js.erb file:

<%= f.fields_for :genre do |g| %>
 <div class="field">
     <%= g.label :name, "Genres" %><br />
     <%= g.text_field :name, :id => 'genre_field' %>
 </div>
<% end %>

<script>
    $("#genre_field").tokenInput(<%= genres_path %>);
</script>
0

精彩评论

暂无评论...
验证码 换一张
取 消