Last active
August 29, 2015 14:10
-
-
Save tschmidt/3c869f17f4f23ab14fe1 to your computer and use it in GitHub Desktop.
Favoriting System
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can also return the number of times a project has been added to favorites:
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: