actionscript 3 - Activerecord Rails 4 perform something like a join that still returns rows that don't have the association -
if after reading question have suggestion better title, please add comment. having trouble succinctly saying wanted. have situation 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 query on artists
return result if either artist's name or album title artist associated match query. can achieve join.
artist.joins(:albums).where("artists.name ? or albums.title ?", query, query).uniq
what know how return artists
name matches query not happen have albums
associated them. goal in single query, prefer not perform 2 sequential queries.
please ask more clarification if need it.
it seems left outer join
looking for. created scopes in models this:
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
i use scope in query:
artist.joins_albums.where("artists.name ? or albums.title ?", query, query).uniq
now results include artists
names match query if not have albums
associated them.
Comments
Post a Comment