Note that there are some explanatory texts on larger screens.

plurals
  1. PORuby complex query elegant solution
    primarykey
    data
    text
    <p>in my rails 4 project, I have the following tables <img src="https://i.stack.imgur.com/kiIN9.png" alt="enter image description here"></p> <p>In this <a href="https://stackoverflow.com/questions/19248761/join-query-by-date-and-primary">SO question</a>, I searched for a SQL query to fetch the <em>projects</em> with the actual <em>project status id</em> = XX. By actual, I mean the one with the max(created_at).</p> <p>I got an answer for my query which is</p> <pre><code>select p.* from projects p left join projects_status_projects psp on (psp.project_id = p.id) where created_at = (select max(created_at) from projects_status_projects where project_id = p.id) and project_status_id = XX </code></pre> <p>My models are defined</p> <pre><code>class Project &lt; ActiveRecord::Base has_many :projects_status_projects has_many :projects_statuses, :through =&gt; :projects_status_projects end class ProjectStatus &lt; ActiveRecord::Base has_many :projects_status_projects has_many :projects, :through =&gt; :projects_status_projects end class ProjectsStatusType &lt; ActiveRecord::Base belongs_to :project belongs_to :project_status end </code></pre> <p>In my <em>Project</em> model, I have the following method</p> <pre><code>def self.with_status(status) joins(:projects_status_projects) .where('projects_status_projects.created_at = (select max(created_at) from projects_status_projects where project_id = p.id)') .where('projects_status_projects.project_status_id = ?', status) end </code></pre> <p>While the query is correct, the received results are well filtered, I find this solution terrible and not elegant at all.</p> <p>Is there any way to get the same result with scopes ?</p> <p>Thanks for your help.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload