开发者

trouble with rails includes query

I am at a loss with this, and cannot figure it out for the life of 开发者_JAVA技巧me :|

Below, @selected_posts represents a query on Posts. I want to query sort users that have posts in @selected_posts. Currently, with the code below I am returning a proper user list of ALL users in the users table. I would get Mike, 5 - Joe, 3 - John, 0 - Jack, 0 -- the zeros show that it is querying every single user (which is going to be a problem. Any suggestions on how to fix the below code to get it to only query the users that have posts in @selected_posts?

@posts = user.includes(@selected_posts).map{ |user|

  [user.name, user.posts.count, user.username]

}.sort

Thanks to any help, I am in debt to you (you have no idea how crazy this has been driving me)


As I undesrstood, you have models: Post and User. User can have many posts. And your goal is to get all user that have posts. You can do it in different ways. For example: define scope in User model

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


Haven't tested it yet, but wouldn't this be more on the line of:

@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

would give you an OrderedHash with users as key and postcount as value.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜