1
\$\begingroup\$

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:

  1. I check if any likes to post available (likes.nil?)
  2. I create users array (users = [])
  3. 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.

\$\endgroup\$
0

1 Answer 1

8
\$\begingroup\$

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
\$\endgroup\$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.