Search code examples
ruby-on-railsjoinwhere-clauseone-to-many

RoR index with where and join : how to filter with associated model criterion?


I am trying to to filter some stuff in a RoR index using where and joins.

I have

  • a Project model
  • and a Milestone model which belongs_to Project, and a "date" column

=>

class Milestone < ApplicationRecord
  belongs_to :project
end

and

class Project < ApplicationRecord
  has_many :milestones
end

And I am trying to create a list of projects with all those which have their last milestone in a specific year.

I am trying this but it does not seem to work.

@projects_2021 = Project.joins(:milestones).where("milestones.last.date.year = 2021")

Solution

  • Try something like this:

    Projects.joins(:milestones).where(milestones: { column_name: "aaa" })