I have projects with many materials and I am trying to make a chain of scope to filter them:
project1 associated with paper . project2 associated with plastic
if the user click on paper I want that project1 and project2 are displayed. If after this first query user click on plastic I want to filter the first query result with the new constraint.
In other word if I select paper and plastic I only want to have project2 displayed.
My models:
Project model
class Project < ApplicationRecord
has_many :project_materials
has_many :materials, through: :project_materials
scope :with_materials, -> (materials) { includes(:materials).where(materials: {id: materials} ) }
end
Material Model:
class Material < ApplicationRecord
has_many :project_materials
has_many :projects, through: :project_materials
end
project_material Model:
class ProjectMaterial < ApplicationRecord
belongs_to :project
belongs_to :material
end
I tried the following in the rails console:
p1 = Project.first
p2 = Project.last
m1 = Material.first
m2 = Material.last
p1.materials << m1
p2.materials << m1
p2.materials << m2
f1 = Project.with_materials(m1)
# which return p1 and p2
f2 = f1.with_materials(m2)
# which return nothings because of the following query
'SQL (1.0ms) SELECT "projects"."id" AS t0_r0, "projects"."name" AS t0_r1, "projects"."difficulty" AS t0_r2, "projects"."status" AS t0_r3, "projects"."duration" AS t0_r4, "projects"."uuid" AS t0_r5, "projects"."slug" AS t0_r6, "projects"."created_at" AS t0_r7, "projects"."updated_at" AS t0_r8, "projects"."project_type_id" AS t0_r9, "materials"."id" AS t1_r0, "materials"."name" AS t1_r1, "materials"."created_at" AS t1_r2, "materials"."updated_at" AS t1_r3 FROM "projects" LEFT OUTER JOIN "project_materials" ON "project_materials"."project_id" = "projects"."id" LEFT OUTER JOIN "materials" ON "materials"."id" = "project_materials"."material_id" WHERE "materials"."id" = 5'
thank you in advance.
I have a solution maybe not the most elegant but at least it's working.
def self.with_materials materials
materials = [materials].flatten.compact
sql = "SELECT project_id, count(material_id) FROM project_materials WHERE material_id IN (?) GROUP BY project_id HAVING count(material_id) > ?"
ids = ProjectMaterial.find_by_sql [sql, (materials), (materials.count - 1)]
ids.collect!{ |i| i.project_id }
where( id: ids )
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.