Home > Software design >  ruby on rails - NoMethodError on has_many relation - trying to create a categories and subcategories
ruby on rails - NoMethodError on has_many relation - trying to create a categories and subcategories

Time:08-22

I am working on a app that will have Categories and Subcategories. So I have created both models with scaffold.

I am getting this error

NoMethodError (undefined method `subcategories' for #<Category::ActiveRecord_Relation:0x00007f96e144d458>)

But the relation is on the model is a has_many and belong_to

Here is my models:

models/category.rb

class Category < ApplicationRecord
  has_many :subcategories
end

models/subcategory.rb

class Subcategory < ApplicationRecord
  belongs_to :category
end

here is the controller

controllers/pages_controller.rb

class PagesController < ApplicationController
  def home
    @categories = Category.all
    @subcategories = @categories&.subcategories || []
  end

  private
    def find_mmy
      @category = Category.find_by(id: params[:category].presence)
      @subcategory = Subcategory.find_by(id: params[:subcategory].presence)
    end
end

And the view views/home.html.erb:

<h1>Pages#home</h1>
<p>Find me in app/views/pages/home.html.erb</p>

<%= turbo_frame_tag "form" do %>
  <%= form_tag root_path, method: :get, data: { controller: "dropdown", action: "change->dropdown#submit" } do %>
    <%= select_tag :category, options_from_collection_for_select(@categories, "id", "name", @category&.id), prompt: "- Please select -" %>
    <%= select_tag :subcategory, options_from_collection_for_select(@subcategories, "id", "name", @subcategories&.id), prompt: "- Model -" %>
  <% end %>

<% end %>

I also created a file called javascript/controllers/dropdown_controller.js

import { Controller } from "@hotwired/stimulus"

// Connects to data-controller="dropdown"
export default class extends Controller {
  submit() {
    this.element.requestSubmit();
  }
}

Sorry, I am beginner, if my question is not clear or missing some information, just help me to make it more clear. thanks

CodePudding user response:

@categories is a collection so you can't call subcategories method for it. You need to call subcategories method for every category like this:

@categories.map(&:subcategories)

this will return an array of arrays so you need to flatten it. also this array may have duplicate record so you need to call uniq method. and you don't need to assign default value as array because it will return array anyway. Here is the final form of the answer:

@categories.map(&:subcategories).flatten.uniq
  • Related