多对多关联查询

时间:2020-10-06 21:33:37

标签: ruby-on-rails activerecord many-to-many associations

我有以下型号:

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

我该如何解决?

1 个答案:

答案 0 :(得分:1)

此:

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指南的Active Record Associations部分中进行了说明。