Clear ORM
  • Welcome to Clear
  • Introduction
    • Setup
  • Model
    • Defining your model
      • Describing your columns
      • Primary Keys
      • Converters
    • Associations
      • belongs_to
      • has_many
      • has_many through
      • has_one
    • Lifecycle
      • Persistence
      • Validations
      • Triggers
    • Batchs operations
      • Bulk update
      • Bulk insert & delete
    • Transactions & Save Points
      • Transaction & Savepoints
      • Connection pool
    • Locks
  • Querying
    • The collection object
      • Filter the query
        • Filter the query – The Expression Engine
        • Find, First, Last, Offset, Limit
        • Aggregation
        • Ordering & Group by
      • Fetching the query
        • Each and Fetch
        • Cursored fetching
        • Model extra attributes
      • Joins
      • Eager Loading
      • Window and CTE
      • Scopes
    • Writing low-level SQL
      • Select Clause
      • Insert Clause
      • Delete Clause
  • Migrations
    • Manage migrations
    • Call migration script
    • Migration CLI
  • Additional and advanced features
    • JSONB
    • Symbol vs String
    • Enums
    • BCrypt
    • Full Text Search
    • Handling multi-connection
  • Other resources
    • API Documentation
    • Inline documentation
    • Github repository
    • Credits
    • Benchmark
Powered by GitBook
On this page
  1. Querying
  2. The collection object
  3. Fetching the query

Model extra attributes

In some case you may want to access a column which is not owned by the model itself. This can be provided by access attributes hash on the model. In this case, you should set the optional argument fetch_columns to true during the fetching:

In the example below, we want to display a the identification document type and number for each person:

People.query.left_join("identification_documents"){ 
    peoples.id == identification_documents.person_id
}.select(
    "people.*", 
    "identification_documents.type AS doc_type",
    "identification_documents.number AS doc_number"
).each(fetch_columns: true) do |x|
    puts "Person #{x.full_name}: " +
         "#{x.attributes["doc_type"]} - #{x.attributes["doc_number"]}"
end

The optional parameter fetch_columns is available in most of the methods where we fetch to one or multiple models.

fetch_columns reduces slightly the performance of the ORM, and that's why it's set to false by default.

This can be combined also with aggregate functions access, like counter:

customers = Customer.query
    .join("shippings"){ shippings.customer_id == customer.id  }
    .select("customers.*", "COUNT(shippings.*) as shipping_count")

customers.each(fetch_columns: true) do |x|
    puts "customer #{x.id} => #{x.attributes["shipping_count"]}"
end
PreviousCursored fetchingNextJoins

Last updated 6 years ago