Has_many relationships in Ruby on Rails 5.0

I have been struggling with a problem in my Rails application for some time now. I have three classes: Products , MerchandiseCategory and MerchandiseMerchandiseCategory . MerchandiseMerchandiseCategory is used to create a many-to-many relationship between two others.

When I run the following commands in the Rails console, I get the corresponding results:

m = MerchandiseMerchandiseCategory.first
# Returns an object that relates the first Merchandise
# with the first Merchandise Category

m.merchandise_category
# Returns the corresponding merchandise_category

m.merchandise_category.merchandise_merchandise_categories.first
# Returns an array of all corresponding MerchandiseMerchandiseCategy ids

m.merchandise
# Returns the corresponding merchandise

m.merchandise.merchandise_merchandise_categories.first
# LoadError: Unable to autoload constant
# Merchandise::MerchandiseMerchandiseCategory, expected
# /home/bjarki/Development/h2/app/models/merchandise/merchandise_merchandise_category.rb
# to define it

So, all relationships work, except for the one-to-many relationship between Merchandise and MerchandiseMerchandiseCategory. I tried everything I could think of, including deleting the Merchandise model and re-creating it.

These are the classes I work with.

merchandise.rb

# branch_id: uuid
# name: string
# price: integer
class Merchandise < ApplicationRecord
  has_many :merchandise_merchandise_categories
  has_many :categories, class_name: :MerchandiseCategory,
                        through: :merchandise_merchandise_categories
  belongs_to :branch
end

merchandise_category.rb

# branch_id: uuid
# name : string
class MerchandiseCategory < ApplicationRecord
  has_many :merchandise_merchandise_categories
  has_many :merchandises, through: :merchandise_merchandise_categories
  belongs_to :branch
end

merchandise_merchandise_category.rb

# merchandise_id: uuid
# merchandise_category_id: uuid
class MerchandiseMerchandiseCategory < ApplicationRecord
  belongs_to :merchandise
  belongs_to :merchandise_category
end

. , - .

+4
2

- , , .

, .

, , , , -, . merchandise_component, , .

- , , : -)

0

merchandise_merchandise_category.rb

///merchandise_merchandise_category.rb

0

Source: https://habr.com/ru/post/1649087/


All Articles