I have the following models:
- User
- Playlist
- SongLike
- Song
- …
When I query a playlist for all of its songs, I get an array of song objects returned. What’s the most efficient way to find out which of these songs a user has “liked”? The likes are stored in the SongLike model:
class SongLike < ActiveRecord::Base
belongs_to :user
belongs_to :song, :counter_cache => "likes_count"
end
…this is the song model:
class Song < ActiveRecord::Base
has_and_belongs_to_many :playlists
has_many :featured_songs
has_many :song_likes
has_many :users, :through => :song_likes
...
end
Utilize your song_likes association along with the songs in memory rather than querying the db multiple times: