首页 > 解决方案 > 多对多关联查询

问题描述

我有以下型号:

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>)

我该如何解决?

标签: ruby-on-railsactiverecordmany-to-manyassociations

解决方案


这个:

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部分中进行了解释。


推荐阅读