Module: Errgonomic::Rails::ActiveRecordFind

Defined in:
lib/errgonomic/rails/active_record_optional.rb

Overview

find and find_by choose their path before any bind exists: an id or a condition the statement cache cannot express is sent to the relation instead. A None has to arrive as nil for that choice, so an absent value asks for IS NULL rather than an equality that can never match.

Instance Method Summary collapse

Instance Method Details

#find(*ids, &block) ⇒ Object

A list of ids is a list of values, so it unwraps one level in: find casts each id it was handed after the query has run, and a wrapper reaching a string primary key's type raises there.

Examples:

first = Note.create!(title: 'Supernova Era')
second = Note.create!(title: 'Ball Lightning')
Note.find([Some(second.id), Some(first.id)]) == [second, first] # => true


693
694
695
# File 'lib/errgonomic/rails/active_record_optional.rb', line 693

def find(*ids, &block)
  super(*ids.map { |id| Errgonomic::Rails.unwrap_options(id) }, &block)
end

#find_by(*args) ⇒ Object

A raw SQL condition is left alone, so an Option interpolated into one still raises rather than binding quietly.

Examples:

note = Note.create!(body: 'Ball Lightning')
Note.find_by(id: note.id, title: None()) == note # => true
Note.find(Some(note.id)) == note # => true


681
682
683
# File 'lib/errgonomic/rails/active_record_optional.rb', line 681

def find_by(*args)
  super(*args.map { |arg| arg.is_a?(Hash) ? Errgonomic::Rails.unwrap_option_values(arg) : arg })
end