Skip to content

Instantly share code, notes, and snippets.

@jwaiswa7
Created November 27, 2020 18:51
Show Gist options
  • Save jwaiswa7/a82ba97ca429d6bc66bb0e9c509d5d18 to your computer and use it in GitHub Desktop.
Save jwaiswa7/a82ba97ca429d6bc66bb0e9c509d5d18 to your computer and use it in GitHub Desktop.

a

Post.order(likes_count: :desc).preload(:user).map(&:email).uniq.first(5)

Am assuming the email is unique to every user

b

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 %>

c

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

d

Would add the validation below to the post model:

validates :state, inclusion: { in: %w[draft live pending] }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment