Post.order(likes_count: :desc).preload(:user).map(&:email).uniq.first(5)
Am assuming the email is unique to every user
Controller
def index
@posts = @user.posts.eager_load(:comments)
end
index view
<% @posts.each do |post| %>
<p><%= post.inspect %></p>
<% post.comments.each do |comment| %>
<p><%= comment.inspect %></p>
<% end %>
<% end %>
I would have the models with the relations below:
user model:
has_many :comments
post model:
has_many :comments
comment model:
belongs_to :user
belong_to :post
Would add the validation below to the post model:
validates :state, inclusion: { in: %w[draft live pending] }