Question about a rails behaviour

Hello, my doubt is the following. The line of code below fetches all
the comments made for an specific event:

@comments = @event.event_comments.paginate(:all, :include =>
[:comment_by], :order => "created_at DESC", :page =>
params[:page], :per_page => 10)

As you can see it has a :include => [:comment_by] to include the name
of the user who made the comment.

event_comment model

belongs_to :comment_by, :select => "id, name, lastname", :foreign_key
=> :commentator_id, :class_name => "User"

On my views I have a partial that loops the comments and contains code
similar to this:

comment.comment_by.name

So my question is:

If I don’t put the include on the find method and let the views as
they are, does rails make a new query when it sees something like
comment.comment_by.name. And if that is the case, if I put the include
on the find, am I saving those queries from happening for each comment
later on?

Thanks,

Elioncho

On Wed, Jul 23, 2008 at 12:04 PM, elioncho [email protected] wrote:

As you can see it has a :include => [:comment_by] to include the name

comment.comment_by.name

So my question is:

If I don’t put the include on the find method and let the views as
they are, does rails make a new query when it sees something like
comment.comment_by.name.

Yes. Rails will automatically query the database if you request an
association that is not already loaded.

And if that is the case, if I put the include

on the find, am I saving those queries from happening for each comment
later on?

Yes. You can also verify what SQL queries rails is executing by
looking in the log files.

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