Module: BetterAr::FinderMethods

Defined in:
lib/better_ar/finder_methods.rb

Instance Method Summary collapse

Instance Method Details

#all(opts = {}) ⇒ ActiveRecord::Relation

Breaks down the hash to do a ActiveRecord::Relation query

example:

User.all(:age => 10, :limit! => 2, :offset! => 3, :order! => :name)

is the same as:

User.where(:age => 10).limit(2).offset(3).order(:name)

if the key :conditions is present it will fall back to legacy

any key with the ‘!’ at the end will be assumed to be a sql operator. The key should match either an ActiveRecord::Relation instance method or an ARel predicate.

Implicit joins are supported. example:

User.all(:records => {:name => 'test'})

is the same as:

User.joins(:records).where(:records => {:name => 'test'})

Parameters:

  • Optional (Hash)

Returns:

  • (ActiveRecord::Relation)


25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/better_ar/finder_methods.rb', line 25

def all(opts = {})
  unless relation = better_ar_get_relation
    relation = super().clone
  end

  if opts.is_a?(Hash)
    if opts.empty?
      return relation
    else
      relation = better_ar_apply_sql_clauses(relation, opts)
      relation = better_ar_apply_associations(relation, opts)
    end
  end

  relation.where(opts)
end

#first(opts = {}) ⇒ ActiveRecord::Base

Forces a limit of 1 on the collection

example:

User.first(:age => 10, :name => 'Brian')

is the same as:

User.where(:age => 10, :name => 'Brian').limit(1).first

if the key :conditions is present it will fall back to legacy

Parameters:

  • Optional (Hash)

    follows same convention as #all

Returns:

  • (ActiveRecord::Base)


55
56
57
# File 'lib/better_ar/finder_methods.rb', line 55

def first(opts = {})
  all(opts.merge(:limit! => 1)).to_a.first
end