Activerecord Rails 4 执行类似联接的操作,但仍然有 returns 行没有关联

Activerecord Rails 4 perform something like a join that still returns rows that don't have the association

如果您在阅读我的问题后有更好的标题建议,请添加评论。我很难简洁地说出我想要什么。我有这样的情况。

class Artist < ActiveRecord::Base
  has_many :album_artists
  has_many :albums, :through => :album_artists
end
class Album < ActiveRecord::Base
  has_many :album_artists
  has_many :artists, :through => :album_artists
end
class AlbumArist < ActiveRecord::Base
  belongs_to :album
  belongs_to :artist
end

我想在 artists 上查询 return 如果艺术家的姓名或与该艺术家关联的专辑标题与查询匹配,则结果。我可以通过加入来实现。

Artist.joins(:albums).where("artists.name like ? or albums.title like ?", query, query).uniq

我想知道的是如何 return artists 其名称与查询匹配但碰巧没有任何 albums 与之关联。我的目标是在一个查询中完成所有这些,我不希望执行两个顺序查询。

如果需要,请询问更多说明。

看来LEFT OUTER JOIN就是我要找的。我在这样的模型中创建了范围:

class Artist < ActiveRecord::Base
  has_many :album_artists
  has_many :albums, :through => :album_artists

  scope :joins_albums, -> {joins('LEFT OUTER JOIN "album_artists" ON "album_artists"."artist_id" = "artists"."id" LEFT OUTER JOIN "albums" ON "albums"."id" = "album_artists"."album_id"')}
end

我在查询中使用范围:

Artist.joins_albums.where("artists.name like ? or albums.title like ?", query, query).uniq

现在结果包括 artists,其名称与查询匹配,即使他们没有任何 albums 与之关联。