【发布时间】:2025-12-29 17:00:11
【问题描述】:
我在表单中使用 jQuery 自动完成小部件(我在此处找到:http://jqueryui.com/autocomplete/#multiple)来创建新的“事物”。输入预定的标签以进行选择效果很好,但我不知道如何让小部件从我的“类别”模型的实例中进行选择。换句话说,我想将每个新事物与几个类别相关联。我应该改变什么?
Things 和 Categories has_many of each other:通过中介模型“CategoryThing”。我正在使用 Rails 4.0.10。
事物/new.html.erb:
<h1>Add Something!</h1>
<p>
<%= form_for @thing, :url => things_path, :html => { :multipart => true } do |f| %>
<%= f.text_field :name, :placeholder => "Name of the thing" %>
<br>
<head>
<meta charset="utf-8">
<title>jQuery UI Autocomplete - Multiple values</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
$(function() {
var availableTags = [
<%= Category.pluck(:name).map { |name| "\"#{name}\"" }.join(",\n") %>
];
function split( val ) {
return val.split( /,\s*/ );
}
function extractLast( term ) {
return split( term ).pop();
}
$( "#tags" )
// don't navigate away from the field on tab when selecting an item
.bind( "keydown", function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB &&
$( this ).autocomplete( "instance" ).menu.active ) {
event.preventDefault();
}
})
.autocomplete({
minLength: 0,
source: function( request, response ) {
// delegate back to autocomplete, but extract the last term
response( $.ui.autocomplete.filter(
availableTags, extractLast( request.term ) ) );
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function( event, ui ) {
var terms = split( this.value );
// remove the current input
terms.pop();
// add the selected item
terms.push( ui.item.value );
// add placeholder to get the comma-and-space at the end
terms.push( "" );
this.value = terms.join( ", " );
return false;
}
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="tags">Categories: </label>
<input id="tags" size="50">
</div>
<%= f.label :related_things %>
<%= f.collection_select :related_things, Thing.all, :id, :name %>
<br>
<%= f.label :display_picture %>
<%= f.file_field :avatar %>
<br>
<%= f.submit "Submit", class: "btn btn-primary" %>
<% end %>
</p>
事物/控制器:
class ThingsController < ApplicationController
def show
@thing = Thing.find(params[:id])
@category_things = CategoryThing.all
@thing.categories.build
end
def new
@thing = Thing.new
@things = Thing.all
end
def create
@thing = Thing.new(thing_params)
if @thing.save
redirect_to @thing
else
render 'new'
end
end
private
def thing_params
params.require(:thing).permit(:name, :image_path, :avatar, category_ids: [])
end
end
【问题讨论】:
标签: jquery ruby-on-rails forms model jquery-autocomplete