Albert.Qing Albert.Qing - 2 months ago 10
Ruby Question

Why is this scope's lambda followed by a block?

Here is a method described in the Rails API:

scope(name, body, &block)


This is an example of using that method also described in the Rails API:

class Shirt < ActiveRecord::Base
scope :red, -> { where(color: 'red') } do
def dom_id
'red_shirts'
end
end
end


The question is about the following code:

do
def dom_id
'red_shirts'
end
end


What does it stand for? I can't find any Ruby syntax about a block could follow a lambda. Did I miss something? Thanks for any help.

Answer

In your example, the lambda is the second regular argument to scope and the block is the block argument to scope (not related to the lambda syntax).

The block lets you define what ActiveRecord calls "extensions", methods that can be called on the return value of the association. The method defined in your example would be called like this:

Shirt.red.dom_id

has_many associations can be extended in the same way. This example is a little weird since it has to do with the view layer; extensions are more often used for things like finders and creators.

Comments