Marcin Doliwa
Marcin Doliwa

Reputation: 3659

Calling private method outputs undefined method error

I receive undefined method 'search_type' for the code below. Can you tell me what am I doing wrong here? Probably something with calling private functions, but I can't find what the problem is.

class Entry < ActiveRecord::Base
  attr_accessible :content, :rank, :title, :url, :user_id

  def self.search(params)
    t, o = search_type(params[:type]),search_order(params[:order])
    scope = self

    scope = scope.where(t) if t
    scope.order(o).page(params[:page]).per_page(20)
  end

  private

  def search_order(order)
    return 'comments_count DESC' if order == '1'
    return 'points DESC' if order == '2'

    'rank DESC'
  end

  def search_type(type)
    return nil unless type.present?

    "entry_type = #{type}"
  end
end

In the controller, I have only @entries = Entry.search(params).

Upvotes: 4

Views: 4686

Answers (3)

Pavel
Pavel

Reputation: 4410

Your method is an a class method, you cant use it form instances of your class

Upvotes: 0

Frederick Cheung
Frederick Cheung

Reputation: 84114

It's not to do with the privateness of your methods, but the fact that search is a class method, so when you call search_order from within it, it is looking for a class method called search_order but you've defined search_order as in instance method.

Make your 2 helper methods class methods and you should be ok. if you want them to be private class methods, then

class << self
  def search(...)
  end
  private
  def search_type(...)
  end
  def search_order(...)
  end
end

If you are wondering why @entries.search(...) works it's because I assume that @entries is something like Entry.where(...) ie, a scope and you can call class methods on scopes.

Upvotes: 6

Benjamin Tan Wei Hao
Benjamin Tan Wei Hao

Reputation: 9691

search is defined as a class method, so you should call Entry.search(params) instead of @entries.search(params).

Upvotes: 0

Related Questions