PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, October 21, 2022

[FIXED] How to get relationed models data?

 October 21, 2022     has-many, ruby, ruby-on-rails, ruby-on-rails-4     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing