【发布时间】:2019-12-28 11:51:34
【问题描述】:
我是 Rails 和 Web 开发的新手。我正在尝试在我的类别和子类别表单上创建一个动态表单选择,以便自动加载与所选类别关联的子类别。这是我尝试过但没有奏效的方法。每当我重新加载页面时,即使我选择了一个项目,我也会在下拉列表中列出子类别
路线:
post '/subcategories/find_by_category', to: 'subcategories#find_by_category'
控制器
class SubcategoriesController < ApplicationController
def show; end
def find_by_category
category = Category.find(params[:category_id])
subcategories = category.subcategories.find_all
render json: {subcategories: subcategories}
end
end
型号
class Category < ApplicationRecord
has_many :subcategories
end
class Subcategory < ApplicationRecord
belongs_to :category, required: false
end
查看
<div class="field">
<label class="label">Category</label>
<%= f.collection_select :category_id, Category.all, :id, :name %>
</div>
<div class="field">
<label class="label">Sub Category</label>
<%= f.select :subcategory_id, options_for_select([]) %>
</div>
<script>
$(document).ready(function(){
var getSubcategories = function(category_id){
var subcategories = $('#service_subcategory_id');
$($subcategories).empty();
$.service('/subcategories/find_by_category', { category_id: category_id},
function(data){
$.each(data.subcategories, function(index, subcategory){
var option = $('<option />');
option.attr('value', subcategory.id);
option.text(subcategory.name);
option.appendTo($subcategories);
});
})
};
var getSelectedCategory = function(){
return $('#service_category_id').val();
};
$('#service_category_id').change(function() {
var category_id = getSelectedCategory();
getSubcategories (category_id);
});
getSubcategories(getSelectedCategory());
});
</script>
我在控制台上收到此错误
readyException.js:6 Uncaught ReferenceError: $subcategories is not defined
at getSubcategories (edit:493)
at HTMLDocument.<anonymous> (edit:520)
at mightThrow (deferred.js:97)
at process (deferred.js:139)
【问题讨论】:
标签: javascript jquery ruby-on-rails