Damir Nurgaliev Damir Nurgaliev - 8 days ago 5
Ruby Question

How to refactor ruby code

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 users array.



In the end, I return users.
Help to refactor it, please

Answer

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
Comments