【问题标题】:Fetch records in STI for empty has_many records in rails 4获取 STI 中的记录以获取 rails 4 中的空 has_many 记录
【发布时间】:2015-02-18 09:58:40
【问题描述】:

我有一个模型库,它 has_many :images, as: :imageable,dependent: :destroy 和属于_to :imageable, polymorphic: true 的图像模型。这里使用的是单表继承。现在我想获取并隐藏没有关联图像的画廊。该怎么办?

【问题讨论】:

    标签: ruby-on-rails inheritance hide record


    【解决方案1】:

    如果您只是想最有效地获取所有关联为空的画廊,您可以使用此范围:

    # in Gallery.rb
    
    scope :no_images, -> {
      joins('LEFT OUTER JOIN images ON images.imageable_id = galleries.id).
      group('galleries.id').
      having('count(imageable_id) = 0') }
    

    运行 Gallery.no_images 将返回所有没有关联图像的 Galleryobjects。

    请注意,文档对使用单表继承的多态关联有以下说明:

    结合单表使用多态关联 继承(STI)有点棘手。为了让协会 按预期工作,确保存储 STI 的基本模型 多态关联的类型列中的模型。接着说 对于上面的资产示例,假设有访客帖子和成员 将帖子表用于 STI 的帖子。在这种情况下,必须有一个 在帖子表中键入列。

    因此,请确保您已将 type 列正确设置为正确的值(在您的情况下为“图像”)。

    【讨论】:

      【解决方案2】:

      试试这个

      Gallery.all.each do |gallery|
         galleries << gallery if (gallery.images.empty?)
      end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-01-01
        • 1970-01-01
        • 2014-06-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-13
        相关资源
        最近更新 更多