Skip to content

Instantly share code, notes, and snippets.

@tschmidt
Last active August 29, 2015 14:10
Show Gist options
  • Save tschmidt/3c869f17f4f23ab14fe1 to your computer and use it in GitHub Desktop.
Save tschmidt/3c869f17f4f23ab14fe1 to your computer and use it in GitHub Desktop.
Favoriting System
class Project < ActiveRecord::Base
has_many :favorites, as: :favorited
has_many :fans, through: :favorites, source: :user
end
# note: the key you use for the user has_many can really be anything you want. Try and use something that describes what the
# assocation is, though.
#
# You can now do the following in order to retrieve the users who have favorited a particular project.
#
# project = Project.first
# project.fans #=> #<ActiveRecord::Associations::CollectionProxy [#<User id:...]>
#
# You can then loop through each of the users like so
#
# project.fans.each do |user|
# puts user.name
# end
@tschmidt
Copy link
Author

You can also return the number of times a project has been added to favorites:

project = Project.first
project.favorites.count

This number reflects all associations that have the ability to favorite a project. If you only want the number of times the project has been favorited by a user object, you can do this instead:

project = Project.first
project.fans.count

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment