AfterWorkGuinness
AfterWorkGuinness

Reputation: 1850

Use instance method in ActiveRecord where clause

I have an instance method that has logic I want to use in a query. My attempts have not worked. I'd rather not duplicate the logic inside is_thing when building my where clause.

class Foo < ActiveRecord::Base

  def is_thing?
    #... some logic
  end

end

I tried

Foo.where(is_thing?)

and got

NoMethodError: undefined method `is_thing?' for main:Object

Upvotes: 3

Views: 3825

Answers (2)

Yana Agun Siswanto
Yana Agun Siswanto

Reputation: 2032

The Approach I would recommend

I do believe that method is not good practice (to chain a where query). It will only add unnecessary complexity.

The better approach is using scope

scope :is_thing?, -> { where(thing: true) }

and call it

Foo.is_thing?.where()

The Why

The reason it is returned

NoMethodError: undefined method `is_thing?' for main:Object

Is because is_thing? is instance variable of Foo

Instance variable can be called on an instance of the class. And not availabe on main object.

You, however could do

Foo.where(Foo.new.is_thing?)

It is posible to use that if you convert is_thing? to class method. e.g

def self.is_thing?
  # code
end

and use it this way

Foo.where(Foo.is_thing?)

Upvotes: 2

sa77
sa77

Reputation: 3603

try this:

class Foo < ActiveRecord::Base

  def is_thing?
    #... some logic
  end

  def things
    Foo.where('thing_check = ?', self.is_thing?)
  end

end

create another instance method to wrap your where query. Then access it as Foo.last.things

Upvotes: 0

Related Questions