andy
andy

Reputation: 2399

Using a model method in a where statement

I have a method in a model that returns a number by counting children and doing various wizardry. It works but I need to use it in a where method:

Product.joins(:owner).where('owner.budget > 0')

owner.budget is a method on the owner model. Is there anyway to use that in the above?

Thanks

Upvotes: 1

Views: 112

Answers (2)

Rafa Paez
Rafa Paez

Reputation: 4860

No, if owner.budget is an instance method on the Owner model. You have to create either a scope or a class method in your Owner class.

Supposing that budget is a column of the owners table, you define this class method in the Owner model

  def self.with_budget
    where('budget > 0')
  end

And then call it that way

  Product.joins(:owner).with_budget

Upvotes: 0

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230286

If this method (owner.budget) does complex computation and/or does not map directly to a database column, then you can't use it in in where clause like this. You can, however, do this:

Product.joins(:owner).to_a.select{|p| p.owner.budget > 0 }

Note that this will load all products into memory and filter them in the application.

Upvotes: 1

Related Questions