views:

66

answers:

2

Are there any shortcuts in Rails' ActiveRecord that enables you to search by value of a field?

For instance, let's say I have a 'user' who can be active or inactive. Is there a nice way of doing User.active? or do I need to do User.find_by_active(1)

Does this also apply to fields that may have many different values, such as a state column? e.g Ticket.open, Ticket.closed?

A: 

Answering my own question here:

Named Scopes:
http://ryandaigle.com/articles/2008/3/24/what-s-new-in-edge-rails-has-finder-functionality

Neil Middleton
+1  A: 

If the active attribute is a boolean column in the database then you can simply call User.active? and it will return true or false depending on the value of the boolean.

In the case of the a state column this will not work. However you could create methods for the User model like...

def open?
  true if self.state == "open"
end

def closed?
  not open?
end
nutcracker
The open? method can just return self.state == "open" - no need for the explicit true.
John Topley