Will you please help me with a ActiveRelation that requires nested joins using scopes?

I am new to rails. Having a blast. The query API though is giving me some trouble. I've been zooming and doing a lot of stuff very quickly, but this is the first time I have spent hours trying to figure it out. It's not like anything I've used before - regular SQL, or Hibernate, or whatever.

The model I have is pretty simple.

A PrivateMessage has many Recipients A Recipient has a Receiver (which of class User) - recipient also has fields for 'is_read' and 'is_deleted'

My goal is to build a query that finds all the unread and not deleted private messages for a given user. To accomplish this, we need to join 'private_messages' to 'recipients'... and then 'recipients' to 'users'.

My Recipient model has the following relevant code:

  belongs_to :receiver, :class_name => 'User', :foreign_key => "receiver_id"   belongs_to :private_message

  scope :unread, where(:is_read => false).where(:is_deleted => false)   scope :unread_by_receiver_id, lambda { |id| unread.joins(:receiver).merge(User.by_id(id)) }

When tested in isolation, this works 100%.

However, when I code the private message queries, I run into problems.

  belongs_to :sender, :class_name => 'User'   has_many :recipients, :class_name => 'Recipient'

  scope :sorted, order("private_messages.created_at desc")   scope :newest, sorted.limit(3)   scope :newest_unread_by_user_id, lambda {       >id> newest.joins(:recipients).merge(Recipient.unread_by_receiver_id(id)) }

When I try and use 'newest_unread_by_user_id, I get the following exception:

    ActiveRecord::ConfigurationError: Association named 'user' was not found; perhaps you misspelled it?

This doesn't make much sense to me... because if the name was spelled wrong, why doesn't it fail when I test it isolation?

Can someone help me out please? This one is driving me nuts. At times like this, I just want to program in full sql and be done with it :frowning:


Here's the relevant User model code:

  has_many :sent_messages, :class_name => PrivateMessage, :foreign_key => 'sender_id'   has_many :recipient_of_messages, :class_name => Recipient, :foreign_key => 'receiver_id'

  scope :by_id, lambda { |id| where(:id => id) }

I also put this on stackoverflow if you want to get some points:

It also looks better on there.