SQL calls and associations

Hi all,

I have a really quick question on the number of SQL calls I am seeing in
my development log when it comes to associations. This may just be an
environment issue, but I could not find an answer.

If I have a belongs_to association for books to a library for example.

class Library < ActiveRecord::Base
has_many :books
end

class Book < ActiveRecord::Base

end

Peer A. wrote:

end

class Book < ActiveRecord::Base

end

Could you elaborate on the problem more? What are you calling in your
application that seems to be generating a lot of extra SQL calls?

@library = Library.find(10)

Something like this?

@library.books.each {}

If so, you might look at the :include option for .find() which will
prevent a lot of extra queries.

-Robby


Robby R.
http://www.robbyonrails.com/

Hi all,

Sorry about the previous message I accidentally sent it before
completing it.

I have a really quick question on the number of SQL calls I am seeing in
my development log when it comes to associations. This may just be an
environment issue, but I could not find an answer.

If I have a belongs_to association for books to a library for example.

class Library < ActiveRecord::Base
has_many :books
end

class Book < ActiveRecord::Base
belongs_to :library
end

If I am iterating over a collection of books in a view like so,

<% for b in @books %>
<%=h b.name %>,
<%= b.library.name %>
<%= b.library.city %>, <%= b.library.state %>
<% end %>

For each time through the loop there are 3 SQL call for the Library
information. One for each of the outputs where the Library is
referenced. Is this how this is supposed to work? Again, this is all
in a development environment, does the production behave differently?
Or, is there some kind of caching mechanism I am not taking advantage
of?

Thanks,

Peer

On 4/25/07, Peer A. [email protected] wrote:

Hi all,

Sorry about the previous message I accidentally sent it before
completing it.

I have a really quick question on the number of SQL calls I am seeing in
my development log when it comes to associations. This may just be an
environment issue, but I could not find an answer.

[…]

http://railscasts.com/episodes/22 is what you’re looking for.

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