title: Rails way: Finding a deeply nested association with many where clause
body: <p>This seems like a simple question but it's a little puzzle to me. I want to find a good way to handle this. 
  I have 5 models.  </p>
  
  <p>Job</p>
  
  <pre><code>class Job &lt; ActiveRecord::Base
    has_many :job_entries_jobs
    has_many :job_entries, through: :job_entries_jobs
  end
  </code></pre>
  
  <p>JobEntry</p>
  
  <pre><code>class JobEntry &lt; ActiveRecord::Base
      has_many :attachments
      has_many :job_entries_jobs
      has_many :pinned_entries, through: :job_entries_jobs
      has_many :jobs, through: :job_entries_jobs
      belongs_to :user, class_name: 'User', foreign_key: 'user_id'
  end
  </code></pre>
  
  <p>JobEntriesJob</p>
  
  <pre><code>class JobEntriesJob &lt; ActiveRecord::Base
    self.table_name = 'job_entries_jobs'
    has_many :pinned_entries
    belongs_to :job_entry
    belongs_to :job, touch: true
  end
  </code></pre>
  
  <p>PinnedEntry</p>
  
  <pre><code>class PinnedEntry &lt; ActiveRecord::Base
    self.table_name = "pinned_entries"
    belongs_to :job_entries_job
    has_and_belongs_to_many :users
  end
  </code></pre>
  
  <p>User </p>
  
  <pre><code>class User &lt; ActiveRecord::Base
    has_many :job_entries
    has_many :pinned_entries
  end
  </code></pre>
  
  <p>Can I get pinned_entries by using <code>job_id</code> and <code>user_id</code> ( job_id and user_id get from <code>request</code> params) via <code>associations</code> in the <code>rails</code> way ( I can get pinned_entries by using <code>SQL</code> ). If Yes, where should I put this <code>code</code>? </p>
  
  <p>How about if I have an <code>attachment</code> model </p>
  
  <pre><code>class Attachment &lt; ActiveRecord::Base
      self.table_name = 'attachments'
  
      belongs_to :job_entry, :class_name =&gt; 'JobEntry', :foreign_key =&gt; 'job_entry_id'
  
  end
  </code></pre>
  
  <p>And I want to <code>include</code> <code>attachment</code> ( a link and file name ) and  <code>JobEntry</code> ( <code>content</code> ) ? 
  Here is the output that should be</p>
  
  <pre><code>{
    "listPinnedEntries": [
      {
        "id": 1
        "user_id": 
        "text": "content of entry",
        "user": {
          "id": 
          "username": "jamesnguyen"
        },
        "attachments": [
          {
            "id": 
            "job_entry_id":
            "comment": "file name",
            "file": {
              "url": "link here"
            }
          },
          {
           "id": 
            "job_entry_id":
            "comment": "file name",
            "file": {
              "url": "link here"
            }
          }
        ]
      }]
  }
  </code></pre>
  
  <p>Thanks for your help</p>