Clear ORM
Search…
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:
1
People.query.left_join("identification_documents"){
2
peoples.id == identification_documents.person_id
3
}.select(
4
"people.*",
5
"identification_documents.type AS doc_type",
6
"identification_documents.number AS doc_number"
7
).each(fetch_columns: true) do |x|
8
puts "Person #{x.full_name}: " +
9
"#{x.attributes["doc_type"]} - #{x.attributes["doc_number"]}"
10
end
Copied!
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:
1
customers = Customer.query
2
.join("shippings"){ shippings.customer_id == customer.id }
3
.select("customers.*", "COUNT(shippings.*) as shipping_count")
4
5
customers.each(fetch_columns: true) do |x|
6
puts "customer #{x.id} => #{x.attributes["shipping_count"]}"
7
end
Copied!
Copy link