Search code examples
ruby-on-railsactiverecordmany-to-manyassociations

Many-To-Many Association Query


I have the following models:

class Restaurant < ApplicationRecord
  has_one_attached :image
  has_many :categories, through: :restaurant_category
end

class Category < ApplicationRecord
  has_many :restaurants, through: :restaurant_category
end

class RestaurantCategory < ApplicationRecord
  belongs_to :restaurant
  belongs_to :category
end

I would query in one shot all the categories associated to a restaurant. SOmething like this:

a = Restaurant.find(1)
a.restaurant_category 

But I have:

NoMethodError (undefined method `restaurant_category' for #<Restaurant:0x00007f5214ad2240>)

How can I solve it?


Solution

  • This:

    class Restaurant < ApplicationRecord
      has_one_attached :image
      has_many :categories, through: :restaurant_category
    end
    

    ... should look like this:

    class Restaurant < ApplicationRecord
      has_one_attached :image
      has_many :restaurant_categories
      has_many :categories, through: :restaurant_categories
    end
    

    Similarly, this:

    class Category < ApplicationRecord
      has_many :restaurants, through: :restaurant_category
    end
    

    ... should look like this:

    class Category < ApplicationRecord
      has_many :restaurant_categories
      has_many :restaurants, through: :restaurant_categories
    end
    

    Which you would use like:

    restaurant_categories = Restaurant.find(1).categories
    

    This is all explained in the has_many :through section of the Active Record Associations guide.