Named regions can be chained, so you make it more complicated for yourself than you need.
Below, when defined in a custom model, you will get what you want:
class User < ActiveRecord::Base ... named_scope :filter_by_name, lambda { |name| {:conditions => { :name => name} } } named_scope :active, :conditions => {:active => true} named_scope :inactive, :conditions => {:active => false} named_scope :have_logged_in, :conditions => {:logged_in => true} end
Then the following fragments will be executed:
active_users = Project.find(1).users.active some_users = active_users.filter_by_name( ["Pete", "Alan"] other_users = active_users.filter_by_name "Rob" logged_in_users = Project.find(1).users.have_logged_in more_users = logged_in_users.filter_by_name "John"
I see that you are using detect , perhaps in order to avoid excessive hits in the database. But your examples do not use it properly. Detect returns only the first element in the list for which the block returns true. In the above example, some_users will only have one entry, the first user called either βPeteβ or βAlanβ. If you want to get all users with the name "Pete" or "Alan", then you want to select . And if you want select , you better use a named scope.
Named regions during evaluation return a special object containing the components necessary for constructing an SQL statement to generate results, while a chain of other named regions has not yet performed the statement. Until you try to access the methods in the result set, for example, call each or map.
source share