How to set the elements selected in an autocomplete field
I have users pick genres from an autocomplete field. This field is in the edit view of the profile, so I have accepts_nested_attributes_for :genres
in the Profile model. Also, Genre and Profile have a has_and_belongs_to_many
association with one another. My question is how do you take t开发者_开发问答he genres that the user picks and set them for that user's profile? What kind of controller code would I need? Would the code go in the profiles or genres controller?
I'm using this for autocomplete: http://loopj.com/jquery-tokeninput/ I've already prepopulated the genres table and hooked up the script to the text field. Right now when a user types, the autocomplete successfully displays suggestions. Now I want to update the database with the selected genres. This database is a join table between genres and profiles. How and where do I do this?
To sum up, I want to save the association between the profile id and the ids of the genres selected into the join table when I click the button in the profile edit view. Right now I get this error:
ActiveRecord::UnknownAttributeError in ProfilesController#update
unknown attribute: genre
Rails.root: /rubyprograms/dreamstill
app/controllers/profiles_controller.rb:18:in `update'
app/controllers/profiles_controller.rb:17:in `update'
Here's my profile edit view:
<%= form_for(:profile, @profile, :url => {:controller => "profiles", :action => "update"}, :html => { :multipart => true, :method => :put }) do |f| %>
...
<%= f.fields_for :genre do |g| %>
<div class="field">
<%= g.label :name, "Genres" %><br />
<%= g.text_field :name, :id => 'genre_field' %>
</div>
<% end %>
...
<div class="action">
<%= f.submit :profile, :value => "Update Profile" %>
</div>
<% end %>
Check this page http://loopj.com/jquery-tokeninput/demo.html
In this page clicking on submit alerts ids of the element, as per my understanding.
The script below in head
does it
<script type="text/javascript">
$(document).ready(function() {
$("input[type=button]").click(function () {
alert("Would submit: " + $(this).siblings("input[type=text]").val());
});
});
</script>
This mat help you.. Basically there is an hidden text field which stores ids of the selected elements
精彩评论