2015-06-13 6 views
0

如果在阅读我的问题后,您有更好的标题建议,请添加注释。我无法简洁地说出我想要的东西。我有这样的情况。Activerecord Rails 4执行类似于连接的事情,仍然返回没有关联的行

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查询返回的结果如果任何艺术家的名字或专辑标题,艺术家与匹配查询相关。我可以通过连接来实现这一点。

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

我想知道的是怎么也返回artists其名称的查询相匹配,但不碰巧有与它们相关的任何albums。我的目标是在单个查询中完成这一切,我不希望执行两个连续查询。

如果您需要,请索取更多说明。

回答

0

看来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相关跟他们。

相关问题