多对多关联查询

Many-To-Many Association Query

我有以下型号:

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

我会一次性查询与餐厅相关的所有类别。像这样的东西:

a = Restaurant.find(1)
a.restaurant_category 

但我有:

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

我该如何解决?

这个:

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

...应该是这样的:

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

同样,这个:

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

...应该是这样的:

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

你会使用哪个:

restaurant_categories = Restaurant.find(1).categories

has_many :through section of the Active Record Associations 指南中对此进行了全部解释。