Issue
I have the model User, Status and Like.
Where:
User has many Statuses
Status has many Likes
How can I get the count of likes that a User has of all status?
For example, user has 2 statuses that each of these has 10 likes. How can I get the total number? (20likes) ?
Solution
Like.joins(status: :user).where(status: { user: user }).count
Another option is to add
has_many :likes, through: :statuses
on your User model. Then you can access a user's statuses likes with:
user.likes
and count them with:
user.likes.count
You might want to rename the association to something more descriptive, since this isn't actually a user's likes. Check out the rails documentation for has_many to see how to do this.
Answered By - Cameron Martin Answer Checked By - Willingham (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.