Is it magic?

Ok, I have a silly question. How does Rails know to generate SQL from
this:

@comment = @post.comments.find(params[:id])

If @post.comments.class is Array then how does Array know to write SQL
with something like my_array.find(1)?

Does Rails add something to Ruby’s Array class to handle that?

In any case it works. I am just curious how it does.

Never mind, I get it now. It’s has_many that adds the needed
collection methods to generate the needed SQL.

On 9/21/07, Robert W. [email protected] wrote:

Never mind, I get it now. It’s has_many that adds the needed
collection methods to generate the needed SQL.

Robert, theres a lot more to it than that. Enough more that
you were nearly right in the subject line.

I don’t know the full details, but Find does not return an Array.
It returns a Proxy object, which looks like (quacks like) an
Array.

ActiveRecord will also add dynamic finders at runtime, with some
more method_missing? cleverness. Its probably well worth your
time to study ActiveRecord in detail. Rails gets most of its magic
from it, and you will find a lot of solid resources behind this.

Also ActiveRecord can be used outside of Rails and very easily too;
making it a useful general purpose tool for even ad-hoc scripting.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs