Reputation: 593
Can .where
in active record take a method as an argument?
def not_foo?
name != "foo"
end
The below code does not work, but you'll see what I mean:
array.where(|element| element.not_foo?).count
Upvotes: 1
Views: 75
Reputation: 1779
The pass around methods as arguments, that is functional paradigm. In Ruby that is achieved by closures
.
Closures
can be implemented in Ruby through blocks
, lambdas
, procs
.
Upvotes: 2
Reputation: 12514
Can .where in active record take a method as an argument?
Ans: No, it cannot. may be you want to do this
array.where.not(name: 'foo').count
Upvotes: 3
Reputation: 2051
You're mixing several different concepts here.
You can't "pass a method as an argument" in Ruby as you would in C or other languages. You can pass a block
as an argument, which is very different.
In your example, element.not_foo?
would be evaluated first. You are passing the result of that evaluation to where
. There are, however, some problems in your code which would prevent it from even running:
The definition of not_foo?
receives an argument (def nor_foo?(v)
) but you passed none, which would raise an ArgumentError: wrong number of arguments (0 for 1)
exception.
You are using block argument syntax (|element|
) incorrectly. In any case, ActiveRecord's where
doesn't accept a block.
Upvotes: 1