Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/60.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql Rails如何通过关联的ID包含数组查找记录_Sql_Ruby On Rails - Fatal编程技术网

Sql Rails如何通过关联的ID包含数组查找记录

Sql Rails如何通过关联的ID包含数组查找记录,sql,ruby-on-rails,Sql,Ruby On Rails,课程有许多标记,由has_和_所属,现在给定两个标记id,[1,2],如何查找所有同时具有这两个标记的课程 [1,2]中的Course.joins:tags.wheretags.id将返回包含其中一个标记的记录,而不是我想要的 # app/models/course.rb has_and_belongs_to_many :tags # app/models/tag.rb has_and_belongs_to_many :courses 由于您使用的是PostgreSQL,因此可以使用AL

课程有许多标记,由has_和_所属,现在给定两个标记id,[1,2],如何查找所有同时具有这两个标记的课程

[1,2]中的Course.joins:tags.wheretags.id将返回包含其中一个标记的记录,而不是我想要的

# app/models/course.rb
has_and_belongs_to_many :tags



# app/models/tag.rb
has_and_belongs_to_many :courses

由于您使用的是PostgreSQL,因此可以使用ALL运算符,而不是IN运算符,如下所示:

Course.joins(:tags).where("tags.id = ALL (?)", [1, 2])

这应该使用AND而不是OR来匹配所有ID。

这不是一个单一的请求,但可能与其他解决方案一样快,并且可以用于任意数量的标记

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)

我猜它会返回所有带有tags.id=1和tags.id=2的记录。可能不起作用,因为tags是一个关联,id不能等于1,同时等于2,用它们的关联发布你的模型。试试这门课程。joins:tags.wheretags.id=>[1,2]你在使用PostgreSQL吗?如果是这样,您可以使用operator.still not work:Course.joins:tags.wheretags.id ALL[1,2]:选择课程。*从课程内部连接课程\u标记上的课程\u标记。课程\u id=课程。id=课程\u标记。标记\u id何处标记。id所有1,2 ActiveRecord::语句无效:PG::SyntaxError:错误:语法错误位于或靠近所有第1行:…gs.id=课程\u标记。标记\u id何处标记。id所有1,2^谢谢,我忘了where字符串后面的。我想你也需要使用运算符…编辑我的答案。使用PostgreSQL数组语法:Course.joins:tags.wheretags.id=ALL,{1,2}这很有效,谢谢,我要等一段时间看看是否有更好的答案