Rails problem includes query

I am in difficulty with this, and cannot understand it for the life of me: |

Below, @selected_posts presents a request for Posts . I want to request sorting users who have posts in @selected_posts . Currently, with the code below, I am returning the correct list of ALL users in the users table. I get Mike, 5 - Joe, 3 - John, 0 - Jack, 0 - zeros indicate that it asks for each user (which will be a problem). Any suggestions on how to fix the code below to get it asks only users who have posts in @selected_posts ?

 @posts = user.includes(@selected_posts).map{ |user| [user.name, user.posts.count, user.username] }.sort 

Thanks for any help, I owe it to you (you have no idea how crazy it turned me on)

+4
source share
2 answers

Like me undesrstood, you have models: Post and User. A user can have many posts. And your goal is to get all users who have messages. You can do this in many ways. For example: define an area in a user model

 scope :with_posts, -> { joins(:posts) } 
+2
source

Not tested it yet, but won't it be more on the line:

 @users = User.joins(:posts).where(:posts => {:category => "Baseball"}) 

Just for completeness and because I like the result:

 @users = Post.where(:category => "one").group(:user).count 

will provide you with an OrderedHash with users as a key and postcount as a value.

+1
source

All Articles