I am new to rails and web development. I am trying to create a dynamic form select on my category and subcategory form such that subcategories associated with a selected category will be automatically loaded. Here is is what I have tried but did not work. Whenever I reload the page I page empty drop downlist the subcategories even if I selected an item
ROUTE:
post '/subcategories/find_by_category', to: 'subcategories#find_by_category'
CONTROLLER
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
MODEL
class Category < ApplicationRecord
has_many :subcategories
end
class Subcategory < ApplicationRecord
belongs_to :category, required: false
end
VIEW
<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>
I get this error on the console
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)
You are calling a different variable than what you have defined.
You wrote:
var subcategories = $('#service_subcategory_id');
$($subcategories).empty();
There are two issues here.
$subcategories
, but you are attempting to reference it.$subcategories
variable in JQuery, which I think would be redundant with what you are trying to do, as the variable above is already a JQuery object. You can name the variable starting with $
if that helps you remember it is a JQuery object, but this should get you to the next blocker:
var $subcategories = $('#service_subcategory_id');
$subcategories.empty();
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.