scopes with lambda and arguments in Rails 4 style?

kaplan picture kaplan · May 16, 2013 · Viewed 95.2k times · Source

I'm wondering how the following is done in Rails 4 or if I just use the Rails 3 approach for using a lambda that can pass an argument the same way with 4 as I do with 3.

I'm pretty new to Rails 3 and trying to work through some samples running Rails 4.

Here is my Rails 3 code:

class Person < ActiveRecord::Base
  scope :find_lazy, lambda {|id| where(:id => id)}
end

# In console I can call
Person.find_lazy(1)

So if this is the Rails 4 way is to use the -> {}, that's a lambda, right? scope :all_lazy, -> { select("*") } What if I needed an argument. I tried a few different ideas and get argument errors in the console when using the -> {}.

Answer

lis2 picture lis2 · May 16, 2013

I think it should be:

scope :find_lazy, -> (id) { where(id: id) }