Search code examples
mysqlruby-on-railsmethodsundefinedfinder

Trouble defining finder method in my application


I’m using Rails 4.2.3 and MySQL 5.5.37. I want to write a finder method for my model, so I have written this (./app/models/user_object.rb):

class UserObject < ActiveRecord::Base

  validates :day, :presence => true
  validates_numericality_of :total
  validates :object, :presence => true

  def find_total_by_user_object_and_year
    UserObject.sum(:total, :conditions => ['user_id = ?', params[:user_id], 'object = ?', params[:object], 'year(day) = ?', params[:year]])
  end

end

However, when I attempt to invoke the method within a controller like so

@my_total = UserObject.find_total_by_user_object_and_year(session["user_id"], 3, @year)

I get the following error

undefined method `find_total_by_user_object_and_year' for #<Class:0x007fb7551514e0>

What is the right way to define my finder method?


Solution

  • Use self.method to define class method:

    def self.find_total_by_user_object_and_year
      sum(:total, :conditions => ['user_id = ?', params[:user_id], 'object = ?', params[:object], 'year(day) = ?', params[:year]])
    end
    

    In this case UserObject inside class method definition is redundant, besause it is same as self. Now you can write:

    UserObject.find_total_by_user_object_and_year(params)