Reputation: 11509
I have a User
model where the users can "favorite" each other. I'm achieving this through a Favoriting
model as a has_many through
relationship to reference User
to itself:
class User < ActiveRecord::Base
has_many :favoriting
has_many :favorites, through: :favoritings, source: :favorited
has_many :favoriteds, class_name: "Favoriting", foreign_key: "favorited_id"
has_many :favoriters, through: :favoriteds, source: :user
...
end
class Favoriting < ActiveRecord::Base
belongs_to :user
belongs_to :favorited, :class_name => 'User'
...
end
This all works great. I can do u.favorites
and get a user's favorites, and I can do u.favoriters
to get the users that have favorited u
. I can also do u.favorites_count
to get the number of favorites.
However, I can't do u.favoriters_count
to get the number of users that have favorited u
.
Any idea if there is access to a built-in method for favoriters_count
or even favoriteds_count
with this type of DB relationship? I could write my own but would rather keep the code base as simple and "Rails-y" as possible.
Upvotes: 1
Views: 73
Reputation: 8331
Have you considered adding a counter_cache
alongside with a favoritings_count
column?
Upvotes: 2
Reputation: 29409
No, the methods added by has_many
are listed in 4.3.1 of http://guides.rubyonrails.org/association_basics.html and do not include a method by this name.
Upvotes: 0