has_and_belongs_to创建的课程has_many标签,现在给定两个标签ID [1,2],如何查找同时具有这两个标签的所有课程
Course.joins(:tags).where("tags.id IN (?)" [1, 2])
将返回具有标签之一的记录,而不是我想要的
# app/models/course.rb
has_and_belongs_to_many :tags
# app/models/tag.rb
has_and_belongs_to_many :courses
这不是一个单独的请求,但是可能仍然与其他解决方案一样快,并且可以适用于任意数量的标签。
tag_ids = [123,456,789,876] #this will probably come from params
@tags = Tags.find(tag_ids)
course_ids = @tags.inject{|tag, next_tag| tag.course_ids & next_tag.course_ids}
@courses = Course.find(course_ids)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句