Rails model relations depending on count of nested relations

Posted by Lowgain on Stack Overflow See other posts from Stack Overflow or by Lowgain
Published on 2010-05-06T18:07:00Z Indexed on 2010/05/06 18:08 UTC
Read the original article Hit count: 385

I am putting together a messaging system for a rails app I am working on. I am building it in a similar fashion to facebook's system, so messages are grouped into threads, etc.

My related models are:

  • MsgThread - main container of a thread
  • Message - each message/reply in thread
  • Recipience - ties to user to define which users should subscribe to this thread
  • Read - determines whether or not a user has read a specific message

My relationships look like

class User < ActiveRecord::Base
    #stuff...
    has_many :msg_threads, :foreign_key => 'originator_id' #threads the user has started
    has_many :recipiences
    has_many :subscribed_threads, :through => :recipiences, :source => :msg_thread #threads the user is subscribed to
end

class MsgThread < ActiveRecord::Base
    has_many :messages
    has_many :recipiences
    belongs_to :originator, :class_name => "User", :foreign_key => "originator_id"
end

class Recipience < ActiveRecord::Base
    belongs_to :user
    belongs_to :msg_thread
end

class Message < ActiveRecord::Base
    belongs_to :msg_thread
    belongs_to :author, :class_name => "User", :foreign_key => "author_id"
end

class Read < ActiveRecord::Base
   belongs_to :user
   belongs_to :message
end

I'd like to create a new selector in the user sort of like:

has_many :updated_threads, :through => :recipiencies, :source => :msg_thread, :conditions => {THREAD CONTAINS MESSAGES WHICH ARE UNREAD (have no 'read' models tying a user to a message)}

I was thinking of either writing a long condition with multiple joins, or possibly writing giving the model an updated_threads method to return this, but I'd like to see if there is an easier way first.

Any ideas? Also, if there is something fundamentally wrong with my structure for this functionality let me know! Thanks!!

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about object-relational-mapping