Johan
Johan

Reputation: 1917

Ruby on Rails: Associations when a user likes a song

I'm trying to figure out the best way to setup my database and models for the following scenario.

A user can like an infinite number of songs. A song can be liked once by an infinite number of users.

I have these tables: songs, users, likes etc... Following RoR conventions.

The table named likes has these foreign keys: user_id, song_id. And also a field named 'time' to save a timestamp when the song was liked.

I'm not sure of how to do this, I would like to be able to use code like this in my controllers:

User.find(1).likes.all This should not return from the likes table, but join the songs table and output all the songs that the user likes.

What are the best practises to achieve this in Ruby on Rails following their conventions?

Upvotes: 0

Views: 260

Answers (1)

nzifnab
nzifnab

Reputation: 16120

Unless you need to act specifically on the likes table data, the model itself is probably not necessary. The relationship is easy:

class User < ActiveRecord::Base
  has_and_belongs_to_many :songs
end

class Song < ActiveRecord::Base
  has_and_belongs_to_many :users
end

This will join through the currently non-existent song_users table. But since you want it to join through likes you can change each one to this:

has_and_belongs_to_many :songs, :join_table => 'likes'

If you want to be able to call User.find(1).likes and get songs, then change the user's version to this:

class User < ActiveRecord::Base
  has_and_belongs_to_many :likes, :join_table => 'likes', :class_name => 'Song'
end

And you could change the songs version to something like this:

class Song < ActiveRecord::Base
  has_and_belongs_to_many :liked_by, :join_table => 'likes', :class_name => 'User'
end

This will give you Song.find(1).liked_by.all and give you the users (You could keep it to users if you wanted using the first version)

More details on habtm relationships can be found here: http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/has_and_belongs_to_many

Edit to add

If you want to act on the join table for whatever reason (you find yourself needing methods specifically on the join), you can include the model by doing it this way:

class User < ActiveRecord::Base
  has_many :songs, :through => :likes
  has_many :likes
end

class Like < ActiveRecord::Base
  belongs_to :user
  belongs_to :song
end

class Song < ActiveRecord::Base
  has_many :users, :through => :likes
  has_many :likes
end

This will let you do User.find(1).songs.all, but User.find(1).likes.all will give you the join data

Upvotes: 3

Related Questions