J
J
john_bob2021-04-11 12:21:10
Ruby on Rails
john_bob, 2021-04-11 12:21:10

Scopes for belongs_to?

there is an example in the Rails Guides documentation

class Book < ApplicationRecord
  belongs_to :author, -> { where active: true }
end


Can you please explain what this part is?
:author, -> { where active: true }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Mirilaczvili, 2021-04-29
@john_bob

The construction means that when association with model membership is performed, a closure (lambda, or just an anonymous method) will be performed, inside which records of authors of books and , whose active property is true, are filtered. In other words: Thus, when searching for a book, RoR will add the rest of the association with the book itself by performing an SQL INNER JOIN between the two tables.
-> { where active: true }:author

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question