Finding users who liked a post I have a method liked_by and it doesn't seem like appropriate as per Ruby style. I need to do it as less as possible.

  def liked_by
    if !object.likes.nil?
      like = Like.where(bonus_id: bonus.id)
      users = []
      like.each do |likes|
        liked_user = User.find_by(id: likes.user_id)
        users.push(liked_user.email)
      end
    end
    return users
  end


The main logic is:


I check if any likes to post available (likes.nil?)
I create users array (users = [])
For each like, I find a user with like.user_id and push this user to the users array


In the end, I return users.
Use joined tables to make more performant database calculations and avoid unnecessary models instantiations.

def liked_by
  return [] unless object.likes.present?
  User.distinct.joins(:likes).where(likes: { bonus_id: bonus.id }).pluck(:email)
end