Help with SQL -> associations (Multiple JOINs)

G

Gleb Mazovetskiy

Is there a way to express this with associations?

@songs = Song.find_by_sql(%Q{
SELECT songs.*, song_playlist_relationships.playlist_id
FROM songs INNER JOIN song_playlist_relationships
ON songs.id = song_playlist_relationships.song_id
WHERE song_playlist_relationships.playlist_id IN
(#{@playlists.collect{|p| p.id}.join(',')})})


Thank you,
Gleb
 
M

Matt H

Is there a way to express this with associations?

=A0 =A0@songs =3D Song.find_by_sql(%Q{
=A0 =A0 =A0 =A0 =A0 =A0SELECT songs.*, song_playlist_relationships.playl= ist_id
=A0 =A0 =A0 =A0 =A0 =A0FROM songs INNER JOIN song_playlist_relationships
=A0 =A0 =A0 =A0 =A0 =A0 =A0ON songs.id =3D song_playlist_relationships.s= ong_id
=A0 =A0 =A0 =A0 =A0 =A0 =A0WHERE song_playlist_relationships.playlist_id= IN
(#{@playlists.collect{|p| p.id}.join(',')})})

Something like this should work. Double-check the :joins option in the
Rails documentation. I might have it wrong.

playlist_ids =3D @playlists.collect{|p| p.id}
Song.find:)all,
:conditions =3D> ["song_playlists_relationships.playlist_id IN (?)",
playlist_ids],
:joins =3D> :song_playlist_relationships)


--=20
Sent via mobile.

--=20
Find me - http://www.smajn.net/social
 
G

Gleb Mazovetskiy

Matt said:
Is there a way to express this with associations?

� �@songs = Song.find_by_sql(%Q{
� � � � � �SELECT songs.*, song_playlist_relationships.playlist_id
� � � � � �FROM songs INNER JOIN song_playlist_relationships
� � � � � � �ON songs.id = song_playlist_relationships.song_id
� � � � � � �WHERE song_playlist_relationships.playlist_id IN
(#{@playlists.collect{|p| p.id}.join(',')})})

Something like this should work. Double-check the :joins option in the
Rails documentation. I might have it wrong.

playlist_ids = @playlists.collect{|p| p.id}
Song.find:)all,
:conditions => ["song_playlists_relationships.playlist_id IN (?)",
playlist_ids],
:joins => :song_playlist_relationships)

Thank you, I'll look into it!


Cheers,

Gleb
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,166
Messages
2,570,901
Members
47,442
Latest member
KevinLocki

Latest Threads

Top