Damir Nurgaliev Damir Nurgaliev - 1 year ago 95
Ruby Question

How to refactor ruby code

I have a method

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)
return users

The main logic is:

  1. I check if any likes to post available (

  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 Source

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download