Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

named_scope and .first?

I can return a collection of objects, with only one (:limit => 1) but is there a way to return the .first() object only, like not within a collection?

named_scope :profile, :conditions => {:association => 'owner', :resource_type => 'Profile'}, :limit => 1    # => collection of 1 profile but I want the profile only NOT in a collection or array

the workaround is simply to apply .first() to the results, but I'd just like to clean up the code and make it less error prone.

like image 721
Andrew Lank Avatar asked Dec 06 '22 21:12

Andrew Lank


1 Answers

You'll probably need to create a class method instead:

def self.profile
  where(:association => 'owner', :resource_type => 'Profile').first
end

Note that with Rails 3 you should be using the where(...) syntax, and that when doing .first, you don't need to specify the limit.

like image 51
Dylan Markow Avatar answered Jan 26 '23 02:01

Dylan Markow