【问题标题】:How to create a scope for an intermediate table?如何为中间表创建范围?
【发布时间】:2014-11-06 12:09:27
【问题描述】:

我有 2 个表,:photos:albums,以及 2 个表之间的匹配表,称为 :photo_listings

我只想显示里面有照片的相册,所以我在相册模型中创建了一个范围:

scope :with_photos, -> {includes(:photos)}

问题是:photos 不是:albums 的直接列,因为照片和相册是 通过:photo_listings 匹配。那么,如何为仅列出已分配照片的相册的相册创建范围?

照片列表模型

class PhotoListing < ActiveRecord::Base
  belongs_to :album
  belongs_to :photo
end

专辑模型

class Album < ActiveRecord::Base
  has_many :photo_listings
end

照片模特

  has_many :photo_listings
  has_many :albums, :through => :photo_listings
  end

【问题讨论】:

    标签: ruby-on-rails scope models


    【解决方案1】:

    您可以将此添加到您的Album

    class Album < ActiveRecord::Base
      has_many :photo_listings
      has_many :photos, through: :photo_listings # this line
    end
    

    那么您的作用域应该可以工作。您只是错过了 Album 模型上的 photos 关系。

    【讨论】:

      猜你喜欢
      • 2019-07-08
      • 1970-01-01
      • 2013-10-07
      • 1970-01-01
      • 2010-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多