<%= f.collection_select :category, Category.all, :id, :name, {prompt: true}
<%= f.collection_select :sub_category, SubCategory.all, :id, :name, {prompt: true} %>
我想根据类别选择仅显示特定于类别的子类别。如何使用jquery在rails上的ruby中实现这一点。
答案 0 :(得分:3)
是的,这是可能的。在类别下拉更改事件中,您必须调用js请求,并且该请求根据您选择的类别返回子类别
$("#category_id").change(function(){
var category_id = $('#category_id').val()
url = "/some_url?category_id=" + category_id
$.get(url, function(data) {
var set_sub_category;
set_sub_category = $("#sub_category_id");
set_sub_category.empty();
opt = $("<option/>");
opt.attr("value", "");
opt.appendTo(set_sub_category);
opt.text("---Select Sub Categories---");
$.each(data, function(index, value) {
var opt;
opt = $("<option/>");
opt.attr("value", value[1]);
opt.text(value[0]);
opt.appendTo(set_sub_category);
});
});
});
控制器看起来像
def some_url
@data = []
@category = Category.find_by(id: params[:category_id])
if @category
@data = @category.sub_categories.map{|b| [b.name,b.id]}
end
render json: @data
end
答案 1 :(得分:1)
您应该添加onChange
功能。
<%= f.collection_select :category, Category.all, :id, :name, {prompt: true}, {onchange: "getSubCategory();"} %>
<%= f.collection_select :sub_category, {}, {prompt: true} %>
将此功能添加到application.js
function getSubCategory() {
var currentCategory = $('#category :selected').val();
$.ajax({
url: '/categories/'+ currentCategory +'/get_sub_categories',
dataType: "json",
success: function(data) {
$('#sub_category').html('');
for (i in data.sub_categories) {
var sub_category = data.sub_categories[i];
if (sub_category != undefined) {
$('#sub_category').append("<option value=\""+sub_category.id+"\">"+sub_category.name+"</option>");
}
}
}
});
}
您还应该添加路线和行动
Route
resources(:categories) do
collection do
get(':category_id/get_sub_categories', action: :get_sub_categories)
end
end
categories_controller.rb
def get_sub_categories
if params[:category_id]
category = Category.find(params[:category_id])
# Assuming you have one-to-many relationship between category and sub_categories.
sub_categories = category.sub_categories
render json: {sub_categories: sub_categories}
end
end
希望这会对你有帮助!