Ruby on Rails Saturday, March 31, 2012

On Sat, Mar 31, 2012 at 10:28 PM, jenna_s <jenna.simmer@gmail.com> wrote:
> Hi,
>
> I'm having trouble with a simple users-messages setup, where users can
> send messages to other users. Here's my class definition:
>
> class Message < ActiveRecord::Base
>  belongs_to :from_user, :class_name => 'User'
>  belongs_to :to_user, :class_name => 'User'
> end
>
> class User < ActiveRecord::Base
>  def messages(with_user_id)
>    Message.where("from_user_id = :id AND to_user_id = :with_user_id
> OR to_user_id = :id AND from_user_id = :with_user_id",
>      { :id => id, :with_user_id => with_user_id })
>      .includes(:from_user, :to_user)
>      .order("created_at DESC")
>  end
> end
>
> When I do some_user.messages(another_user.id), I want to retrieve the
> conversation that some_user has with another_user. I do get back an
> array of Messages, but it doesn't include the eager loading of
> from_user and to_user.

How many SQL queries do you see in the log for

messages = some_user.messages(another_user.id)

(I believe you should see 3 queries if from_user and to_user data
is present).

When asking later on:

messages.first.from_user

is it then launching an SQL for the individual from_user
at that time?

> What am I doing wrong? Am I forced to use
> joins?

It must be possible to get this working with .includes
as you tried.

HTH,

Peter

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.

No comments:

Post a Comment