title: How to query this in Rails?
body: <p>I have a model <code>submission</code> and it <strong>has_many</strong> <code>submissionstate</code> (and two tables <code>submissions</code> and <code>submissionstates</code> respectively).</p>
  
  <p><code>submissionstates</code> has a foreign key <code>submission_id</code> and another <code>state_id</code> column (and <code>updated_at</code>, <code>id</code>)</p>
  
  <p>Every time if there is state change for <code>submission</code>, a new entry with the new state will be created in the <code>submissionstates</code> table.</p>
  
  <p>I want to show entries that has <code>state_id</code> = <strong>0</strong> and the state is the <strong>latest</strong> state of the submission.</p>
  
  <p>For example, a <code>submission</code> has two states (A(state_id = 0) and B (state_id = 1)), B is added after A. So I do <strong>not</strong> want this submission to be shown on the page since even though it has A, it is not the latest state (which is B).</p>
  
  <p>I used:</p>
  
  <pre><code>@submissions = Submission.includes(:submissionstates).where("submissionstates.state_id = 0").all
  </code></pre>
  
  <p>But the result will includes all the state with <code>state_id</code> = 0 even if they are not the latest state of a submission.</p>
  
  <p>What should I change in the query in order to make this work?</p>