I have three models
class Person < ActiveRecord::Base
has_many :assignments
has_many :projects, through: :assignments
end
class Project < ActiveRecord::Base
has_many :assignments
has_many :people, through: :assignments
end
class Assignment < ActiveRecord::Base
belongs_to :person
belongs_to :project
end
I'm using a attribute called 'kind' on the Assignment model to determine how the person is associated with the property. It's a string field and possible values include: 'supervisor', 'worker', 'inspector'.
I've added the attribute to the Assignment model rather than the Person model because in some scenarios its possible for a person to be a worker on one project, and a supervisor on another at the same time.
Its important to note, that when created a supervisor is automatically assigned. Therefore all projects will have at least one assignment already.
What I'm wondering is this:
How do I query all projects which have no workers assigned? This would be a project which has no assignments which have 'worker' in the kind column.
To be efficient you could use a counter_cache column.
class Assignment < ActiveRecord::Base
belongs_to :person
belongs_to :project, counter_cache: true
end
Project.where(assigments_count: 0)
Check the counter_cache part in: Rails guides And note that you will need to reset counter cache column on already created models.
You can use ActiveRecord's joins query method to accomplish this.
Project.joins(:assignments).where('assignments.kind <> ?', 'worker')
This will result in the following query
SELECT "projects".* FROM "projects" INNER JOIN "assignments" ON "assignments"."project_id" = "projects"."id" WHERE (assignments.kind <> 'worker')
Hope this helps. Cheers!
或者,如果您想避免多余的列和数据库更新SQL,请仅使用SQL- 从一个表中查找另一个 + rails raw sql示例中 不存在的记录
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.