user3775217 user3775217 - 19 days ago 5
Ruby Question

Rails 5 - Activerecord association query

I have two models associated with each other as follows.

class Comment < ApplicationRecord
belongs_to :user
end

class User < ActiveRecord::Base
has_many :comments
end


Following record query

comments_list = Comment.where(:post_id => post_id, :is_delete => false).joins(:user).select('comments.*,users.*')


Generates the following mysql query in logger

SELECT comments.*,users.* FROM `comments` INNER JOIN `users` ON `users`.`id` = `comments`.`user_id` WHERE `comments`.`post_id` = '81' AND `comments`.`is_delete` = 0.


This seems generating very ligitimate query, but comments_list object contain columns only from comments table.

Thanks

Answer

It depends on what you want to do, if you want to display the username next to the comment, Mert B.'s answer is fine, all you have to do is include(:user) and the users from the comment list will be fetched along when you do something like this:

comments_list = Comment.where(:post_id => post_id, :is_delete => false).joins(:user).select('comments.*,users.*')
comments_list.each do |comment|
  puts "#{comment.text} by #{comment.user.name}"
end

Or maybe if you want only users who have at least one comment, you can always select users from the user_ids on the comments table:

User.where(id: Comment.select(:user_id))
Comments