Method: OccamsRecord::EagerLoaders::Builder#eager_load_one

Defined in:
lib/occams-record/eager_loaders/builder.rb

#eager_load_one(name, mapping, sql, binds: {}, model: nil, use: nil) { ... } ⇒ Object

Specify some arbitrary SQL to be loaded into some arbitrary attribute (“name”). The attribute will hold either one record or none.

In the example below, :category is NOT an association on Widget. Though if it where it would be a belongs_to. The mapping argument says “The category_id in the parent (Widget) maps to the id column in the child records (Category).

The %category_ids bind param will be provided for you, and in this case will be all the category_id values from the Widget query.

res = OccamsRecord
  .query(Widget.order("name"))
  .eager_load_one(:category, {:category_id => :id}, "
    SELECT * FROM categories WHERE id IN (%{category_ids}) AND name != %{bad_name}
  ", binds: {
    bad_name: "Bad Category"
  })
  .run

Parameters:

  • name (Symbol)

    name of attribute to load records into

  • mapping (Hash)

    a Hash that defines the key mapping of the parent (widgets.category_id) to the child (categories.id).

  • sql (String)

    the SQL to query the associated records. Include a bind params called ‘%ids’ for the foreign/parent ids.

  • binds (Hash) (defaults to: {})

    any additional binds for your query.

  • model (ActiveRecord::Base) (defaults to: nil)

    optional - ActiveRecord model that represents what you’re loading. required when using Sqlite.

  • use (Array<Module>) (defaults to: nil)

    optional - Ruby modules to include in the result objects (single or array)

Yields:

  • eager load associations nested under this one

Returns:

  • self



85
86
87
88
# File 'lib/occams-record/eager_loaders/builder.rb', line 85

def eager_load_one(name, mapping, sql, binds: {}, model: nil, use: nil, &builder)
  @eager_loaders << EagerLoaders::AdHocOne.new(name, mapping, sql, binds: binds, model: model, use: use, &builder)
  self
end