Search code examples
ruby-on-railsinstance-method

rails instance methods not working on relation


I feel like I am making a syntax error.

I am trying to define an instance method in the model, that then gets called with an instance receiver. but the output is nilClass.

What am I doing wrong?

model

class Park < ActiveRecord::Base

  has_many :reviews

  def percentages
    @percentages = Array.new(5, 0)
    if reviews.any?
      5.downto(1).each_with_index do |val, index|
        @percentages[index] = (reviews.with_stars(val).size) * 100 / (reviews_count)
      end
      @percentages
    end
  end

end

controller

class ParksController < ApplicationController

  def show
     @park = Park.find(params[:id])
     @percentages = @park.percentages
  end

end

view

= @percentages[0]

output

undefined method `[]' for nil:NilClass

Solution

  • You should explicitly return the @percentages after the if.

    def percentages
      @percentages = Array.new(5, 0)
      if reviews.any?
        5.downto(1).each_with_index do |val, index|
          @percentages[index] = (reviews.with_stars(val).size) * 100 / (reviews_count)
        end
      end
      @percentages
    end
    

    Moreover, you don't need an instance variable in the method. A simple variable would be enough.

    def percentages
      percentages = Array.new(5, 0)
      if reviews.any?
        5.downto(1).each_with_index do |val, index|
          percentages[index] = (reviews.with_stars(val).size) * 100 / (reviews_count)
        end
      end
      percentages
    end