Search code examples
ruby-on-railsrubysorting

How to sort_by using class method Rails


I'm trying to rank instances using a class method:

@sorted_datsk_hpe = all_datsk_hpe.sort_by { |hpe| Hpe.datsk_point_count(hpe) }

which takes me here:

def self.datsk_point_count(hpe)
    points = 0
    if hpe.gen_ac != ""
      if hpe.gen_aa != nil
        points += hpe.gen_aa.to_i * hpe.gen_acd
      else
        points += hpe.gen_amc.to_i * hpe.gen_acd
      end
    else
      (1..10).each do |num|
        if hpe["ad_c_#{num}"] != ""
          if hpe["ad_c_#{num}_available"] != nil
            points += hpe["ad_c_#{num}_available"].to_i * hpe["ad_c_#{num}_discount"]
          else
            points += hpe["ad_c_#{num}_max_capacity"].to_i * hpe["ad_c_#{num}_discount"]
          end
        end
      end
    end
    points
  end

which gives me

TypeError: String can't be coerced into Integer
    from app/models/hpe.rb:420:in `+'
    from app/models/hpe.rb:420:in `datsk_point_count'
    from (irb):30:in `block in irb_binding'
    from (irb):30:in `sort_by'
    from (irb):30

but if i run the class method on its own with a single instance, it works, so I must be doing sort_by wrong?


Solution

  • The code was right, I just wasn't aware that model code changes requires restarting console, similar to needing to refresh the page when modifying javascript etc.

    This may not be exactly accurate as I am novice, but restarting the console resolved the issue.