rails 多个 has_many 相同模型之间的关系

rails multiple has_many relationships between the same models

我正在尝试找出在 rails 中建立多对一关系模型的最佳方法,其中关系有多个范围。

一个例子是餐厅有很多照片。我希望能够打电话给

restaurant.lounge_photos

并且只收到休息室照片, 而且还可以打电话

restaurant.food_photos

只收到美食照片。

我能想到的两种方法是:

  1. 使用多个连接 table,并对每种类型的照片使用 has_many 到 has_one 的关系。

  2. 给照片模型添加一个'type'属性,写一个scoping方法。

这两个对我来说似乎有点笨拙。 这里有更好的解决方案吗?

我认为你必须去 has_manySingle Table Inheritance(STI),如下.

  1. restaurantphoto建立关联
class Restaurant < ActiveRecord::Base
 has_many :photos
end

class Photo < ActiveRecord::Base
 belongs_to :restaurant
end
  1. 那么你必须在 Photo 模型中使用 STI。原因是 lounge_photosfood_photos.
  2. 几乎所有字段都是通用的

直接使用作用域可以区分它并实现你的目标。

有关使用 STI 的更多详细信息,您可以参考 this link

这是一种方法,使用 type

has_many :food_photos, 
         class_name: 'Photo', 
         foreign_key: :restaurant_id, 
         -> { where(type: 'food') }

has_many :lounge_photos, 
         class_name: 'Photo', 
         foreign_key: :restaurant_id, 
         -> { where(type: 'lounge') }