If after reading my question you have a suggestion for a better title, please add a comment. I was having trouble succinctly saying what I wanted. I have a situation like this.
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
I want a query on artists to return a result if either the artist's name or an album title that the artist is associated with match the query. I can achieve this with a join.
Artist.joins(:albums).where("artists.name like ? or albums.title like ?", query, query).uniq
What I would like to know is how to also return artists whose name matches the query but do not happen to have any albums associated with them. My goal is to do this all in a single query, I would prefer not to perform two sequential queries.
Please ask for more clarification if you need it.
It seems that
LEFT OUTER JOINis what I am looking for. I created scopes in the models like this:I use the scope in the query:
Now the results include
artistswhose names match the query even if they do not have anyalbumsassociated with them.