title: Rails DB structure for messaging system
body: <p>I'm developing a messaging system on rails 3. My database structure is roughly as follows:</p>
  
  <pre><code>users:  
    id  
    name  
  
  messages:  
    id  
    body
  
  users_messages:  
    user_id  
    message_id  
    direction  
    is_read  
    created_at  
  </code></pre>
  
  <p>I think I have to use *has_many :through* association to be able use relationship model:</p>
  
  <pre><code>class User &lt; ActiveRecord::Base
    has_many :user_messages
    has_many :messages, :through =&gt; :user_messages
  end
  
  class UserMessages &lt; ActiveRecord::Base
    belongs_to :users
    belongs_to :messages
  end
  
  class Messages &lt; ActiveRecord::Base
    has_many :user_messages
    has_many :users, :through =&gt; :user_messages
  end
  </code></pre>
  
  <p>I can get all user's messages by calling <code>user.messages</code> and detect incoming/outgoing by direction. I just do not quite understand how I create a relationship that would be able do:  </p>
  
  <p><code>  </p>
  
  <pre><code>  message.sender  
    message.recipient
    user.messages.first.recipient ...
  </code></pre>
  
  <p></code></p>
  
  <p>As well as each message requires at least 2 row in user_messages table:</p>
  
  <pre><code>  user_id_sender , message_id, outgoing ....
    user_id_recipient, message_id, incoming ....  
  </code></pre>
  
  <p>Maybe my database structure is wrong? Can some body suggest more effective design?</p>
  
  <p>Thank you in advance.</p>