Module: SexyScopes::ActiveRecord::QueryMethods

Defined in:
lib/sexy_scopes/active_record/query_methods.rb

Instance Method Summary collapse

Instance Method Details

#where(*args, &block) ⇒ Object

Adds support for blocks to ActiveRecord ‘where`.

The block is evaluated in the context of the current relation, and the resulting expression is used as an argument to ‘where`, thus allowing a cleaner syntax where you don’t have to write the receiver of the method explicitely, in this case: ‘username` vs `User.username`

This form can also be used with relations:

Examples:

User.where { username == 'bob' }
# is equivalent to:
User.where(User.username == 'bob')
post.comments.where { rating > 5 }
# is equivalent to:
post.comments.where(Comment.rating > 5)

Raises:

  • (ArgumentError)

    if both arguments and a block are passed



24
25
26
27
28
29
30
31
32
# File 'lib/sexy_scopes/active_record/query_methods.rb', line 24

def where(*args, &block)
  if block
    raise ArgumentError, "You can't use both arguments and a block" if args.any?
    conditions = instance_exec(&block)
    super(conditions)
  else
    super
  end
end