user456584
user456584

Reputation: 88815

How to query Rails / ActiveRecord model based on custom model method?

Disclaimer: I'm relatively new to rails.

I have a custom method in my model that I'd like to query on. The method, called 'active?', returns a boolean. What I'd really like to do is create an ActiveRecord query of the following form:

Users.where(:active => true)

Naturally, I get a "column does not exist" when I run the above as-is, so my question is as follows:

How do I do the equivalent of the above, but for a custom method on the model rather than an actual DB column?

Upvotes: 2

Views: 3147

Answers (2)

6xth
6xth

Reputation: 87

An easy way to do this would be by using the select method with your exiting model method.

Users.select{|u| u.active}

This will return an array so you won't be able to use Active Record Query methods on it. To return the results as an ActiveRecord_Relation object, you can use the where function to query instances that have matching ids:

class User < ActiveRecord::Base

  def self.active
    active_array = self.select{|r| r.active?}
    active_relation = self.where(id: active_array.map(&:id))
    return active_relation
  end

end

Upvotes: 2

Mark Swardstrom
Mark Swardstrom

Reputation: 18070

Instead of using the active? method, you would have a scope to help find items that match.

Something like this...

def self.active
  joins(:parent_table).where(:archived => false).where("? BETWEEN parent_table.start_date AND parent_table.end_date ", Time.now)
end

And, you should be able to do this

def active?
  User.active.exists?(self)
end

If you would like to reuse this scope for the instance test.

Upvotes: 2

Related Questions