ruby-on-rails - 多对多关联查询
问题描述
我有以下型号:
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部分中进行了解释。
推荐阅读
- r - Rmd 笔记本中节号后的尾随句点
- html - 访问@mixin 中的根变量
- json - 使用 T-SQL 从 Json 文件中检索结果而不是迭代多个子对象
- java - 当输入值都是整数时,为什么 int 会给我一个不同的值?
- dbeaver - 导出文件名
- c# - Visual Studio 不断尝试重新创建 sql 表而不是更新
- c# - 控制台应用程序错误如果找不到要重命名的某个文件
- c# - 利润及其价值
- swiftmailer - Swift_TransportException | 无法与主机 smtp.gmail.com 建立连接 [网络无法访问 #101] laravel 5.7
- firebase - 在flutter中更新firebase插件后代码搞砸了