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" %><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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.