Jack Jack - 23 days ago 5
Javascript Question

JQuery can't find the Sub Category ID

I followed the instructions in this question's answer by emmanuel and the form now finds the Category ID and submits it but does not find the Sub Category ID associated with the Category and does not save it.

The params are taken which can be noted by this,

Parameters: {"utf8"=>"✓", "authenticity_token"=>"PTRTGGblf3HoWNXmanKl8TIP7F4j/QKTLN2Wd6oKSQWSXV27qioztUpXgb6YjHEroaWf8dgTzUIgQiRBK2XxWQ==", "post"=>{"title"=>"200k", "description"=>"FMxd123", "category_id"=>"2", "subcategory_id"=>"9"}, "commit"=>"Create Post"}

It then shows the error message on my screen (with my error partial) that "Sub Category must exist. The SQL output is like so:

(0.2ms) begin transaction
Category Load (0.1ms) SELECT "categories".* FROM "categories" WHERE "categories"."id" = ? LIMIT ? [["id", 2], ["LIMIT", 1]]

(0.0ms) rollback transaction
Rendering posts/new.html.erb within layouts/application
Rendered shared/_errors.html.erb (0.8ms)
Category Load (0.1ms) SELECT "categories".* FROM "categories"
CACHE (0.0ms) SELECT "categories".* FROM "categories"

SubCategory Load (0.1ms) SELECT "sub_categories".* FROM "sub_categories" WHERE "sub_categories"."category_id" = ? [["category_id", 1]]
SubCategory Load (0.1ms) SELECT "sub_categories".* FROM "sub_categories" WHERE "sub_categories"."category_id" = ? [["category_id", 2]]
SubCategory Load (0.1ms) SELECT "sub_categories".* FROM "sub_categories" WHERE "sub_categories"."category_id" = ? [["category_id", 3]]

My Posts.coffee:

jQuery ->
subcat = $('#subcategory-select').html()
$('#category-select').change ->
cat = jQuery('#category-select').children('option').filter(':selected').text()
options = $(subcat).filter("optgroup[label='#{cat}']").html()
if options

And the part where category_id and sub_category_id are taken in the form with select boxes:

<%= f.label :category_id%>
<%= f.collection_select(:category_id, Category.all, :id, :name,
{ prompt: 'Select a category' }, { id: 'category-select' }) %>
<%= f.label :subcategory_id%>
<%= f.grouped_collection_select :subcategory_id, Category.all, :sub_categories,
:name, :id, :name, { include_blank: 'Select a sub category' },
{ id: 'subcategory-select' } %>

Confused as to how it isn't working because it made my category_id get saved when it wasn't working. Any ideas?


Gone through your code and I found some errors.

Here are the changes you should make to make your project work.

As you mentioned, it is not any jquery issue.


You have taken the subcategory model name as SubCategory and table is sub_categories, so the foreign key should be sub_category_id, but you have taken subcategory_id.

So either you have to change the column in the database, or tell rails to take the name.

Here are the changes to tell rails about it.


class Post < ApplicationRecord
  belongs_to :category
  # belongs_to :sub_category
  belongs_to :sub_category, class_name: 'SubCategory', foreign_key: 'subcategory_id'


class SubCategory < ApplicationRecord
  belongs_to :category
  # has_many :posts, :primary_key => "subcategory_id"
  has_many :posts, class_name: 'Post', primary_key: 'id', foreign_key: 'subcategory_id'

Check the lines commented.

Now the post show view also has some errors which I solved.



<% content_for :title, @post.title %>
<% navigation_add @post.title, post_path(@post) %>
<h2 align="center">Title: <%= @post.title %></h2>
<div class="well col-xs-8 col-xs-offset-2">
    <h4 class="center description"><strong>Description:</strong></h4>
    <%= simple_format(@post.description) %>
    <p>Post ID: <%=@post.id%></p>
    <div class="post-actions">
        <%= link_to "Edit this post", edit_post_path(@post), class: "btn btn-xs btn-primary" %>
        <%= link_to "Delete this post", post_path(@post), method: :delete,
        data: { confirm: "Are you sure you want to delete the post?"},
        class: "btn btn-xs btn-danger" %>
        <%= link_to "View all posts", posts_path, class: "btn btn-xs btn-success" %>

Last but not the least, your seeds.rb is wrong.


category_1 = Category.where(name:"cat1").first_or_create(name:"cat1")
category_2 = Category.where(name:"cat2").first_or_create(name:"cat2")
# 1
SubCategory.where(name: 'g', category_id: category_1.id).first_or_create
SubCategory.where(name: 'er', category_id: category_1.id).first_or_create
SubCategory.where(name: 'tu', category_id: category_2.id).first_or_create
SubCategory.where(name: 'dual', category_id: category_2.id).first_or_create

Add this script to posts/new.html to get your dropdown work.

<script type="text/javascript">
$(document).ready(function() {
  var subcat;
  subcat = $('#subcategory-select').html();
  return $('#category-select').change(function() {
    var cat, options;
    cat = jQuery('#category-select').children('option').filter(':selected').text();
    options = $(subcat).filter("optgroup[label='" + cat + "']").html();
    if (options) {
      return $('#subcategory-select').html(options);
    } else {
      return $('#subcategory-select').empty();

Here is the working image:

enter image description here