Class: Babik::Table::Field

Inherits:
Object
  • Object
show all
Defined in:
lib/babik/queryset/lib/field.rb

Overview

Field module abstracts the concept of table field according to some useful conversions

Instance Method Summary collapse

Constructor Details

#initialize(model, field) ⇒ Field

Create an actual field for a model.

Parameters:

  • model (ActiveRecord::Base)

    model this field belongs to.

  • field (String)

    field model that could need the conversion.



13
14
15
16
# File 'lib/babik/queryset/lib/field.rb', line 13

def initialize(model, field)
  @model = model
  @field = field
end

Instance Method Details

#real_fieldString

Check if the field requires some conversion and if that’s the case, return the converted final field If the field is a name of an association, it will be converted to the foreign entity id

Returns:

  • (String)

    Actual name of the field that will be used in the SQL.



21
22
23
24
25
26
27
28
29
30
31
# File 'lib/babik/queryset/lib/field.rb', line 21

def real_field
  # If the selected field is a local attribute return the condition as-is (that's the most usual case)
  is_local_attribute = @model.column_names.include?(@field.to_s)
  return @field if is_local_attribute
  # If the selected field is the name of an association, convert it to be a right condition
  association = @model.reflect_on_association(@field.to_sym)
  # Only if the association is belongs to, the other associations will be checked by foreign filter method
  return association.foreign_key if association && association.belongs_to?
  # Field that is not present in the model
  raise "Unrecognized field #{@field} for model #{@model} in filter/exclude"
end