Spyros
Spyros

Reputation: 48626

What is an ActiveRecord Rails Relation really?

I was trying to understand some of the internals of Rails Relations, in order to use them effectively in queries. Therefore, I opened up a console and did some tests:

ruby-1.9.2-p180 :036 > Skill.where(:second_class => 'Wealth Ranger').map {|att| att.class}
 => [Skill(id: integer, name: string, description: string, second_class: string, third_class: string, created_at: datetime, updated_at: datetime)]

Now, I would not expect that output. I would expect something like Relation or something similar. But it seems like it traverses every attribute and produces the type for each one.

What is a Relation in Ruby's terms really? Is it a totally custom structure? If so, are there similarities between hashes and arrays, or should it be considered like a totally custom structure?

EDIT:

After some more testing, it seems like it just contains objects of that class. Is that how it operates?

Upvotes: 3

Views: 3446

Answers (1)

aNoble
aNoble

Reputation: 7072

ActiveRecord's Relation class in Rails 3 is really just a layer on top of Arel. It handles collecting parameters for "lazy loading" and Rails' simplified query methods (compared to straight Arel).

The best description I've seen of it's inner workings is on Ernie Miller's blog. He wrote meta_search and meta_where so he knows what he's talking about.

Upvotes: 8

Related Questions