On May 11, 2006, at 10:08 AM, Richard W. wrote:
I understand that the belongs_to causes related companies to be read
from the db when I ask for a category. I suspect SQL something like
select * from categories, companies
where category.id = myid
and companies.category_id = category.id
but what SQL results from the has_many?
I would say that you are thinking about this in the wrong way.
Technically the belong_to and the has_many methods don’t specifically
create SQL. What they do is create a programatic link between the two
models that is then expressed as SQL when you request specific data
from the database.
If you do: Company.find(:first), say through script/console, SQL is
generated, but no SQL specific to the belongs_to relationship.
If you do: Company.find(:first).category, you actually create two SQL
requests to the database. The first is to return the first Company
record. The second is to return the parent Category record of that
Company record.
Likewise, if you do: Category.find(:first).companies, you get 2 SQL
requests, the second of which brings back an array of child Company
records.
If you want a deeper understanding of this, there are several things
you should do. First, I recommend getting the Agile Web D.
with Rails book (http://pragmaticprogrammer.com/).
Second, you should read through the API docs on this page:
<Peak Obsession
ClassMethods.html>
Third, you should launch your Rails app under Development, with the
ability to see the WEBrick/lighttpd output, launch script/console and
give some find calls a try, looking at the web server output. In that
output will be the SQL generated by Rails.
-Brian