Ruby on rails ActiveRecord';和';基于可变长度数组的多对多查询

Ruby on rails ActiveRecord';和';基于可变长度数组的多对多查询,ruby-on-rails,arrays,activerecord,Ruby On Rails,Arrays,Activerecord,我正在开发Rails应用程序。我有一个选项id数组,可以有不同的长度。通过答案,选项和用户之间存在多对多关系。鉴于以下模型: class Option < ActiveRecord::Base has_many :answers has_many :users, through: :answers end class User < ActiveRecord::Base has_many :answers has_many :options, through: :an

我正在开发Rails应用程序。我有一个
选项id
数组,可以有不同的长度。通过答案,选项和用户之间存在多对多关系。鉴于以下模型:

class Option < ActiveRecord::Base
  has_many :answers
  has_many :users, through: :answers
end

class User < ActiveRecord::Base
  has_many :answers
  has_many :options, through: :answers
end

class Answer < ActiveRecord::Base
  belongs_to :user
  belongs_to :option
end
我想知道是否有一种更优雅、更简单的方法可以在单个查询和/或不使用循环的情况下获取信息。如果SQL让它变得更好,我会很乐意使用它

谢谢大家!

试试这个:

Option.find(1).用户&Option.find(2).用户


&
是类
Array
的Ruby方法,它将返回任意长度的两个数组的交集

只需使用2个SQL查询即可实现目标(无论
选项\u id
数组的长度如何),方法如下:

option_ids = [1, 2, 3, 4, 5]

# select all the user_id's from the answers table (by joining options and answers tables) 
# based on the option_ids array (1 SQL Query)
user_ids = Option.joins(:answers)
                 .where('answers.option_id IN (?)', option_ids)
                 .select('answers.user_id')

# get the users from the users table (1 SQL Query)  
expected_users = User.find(user_ids)

@波尔罗德:你觉得这个解决方案有用吗?对不起,已经有几天没用了!我喜欢这一个的简单性,但是考虑到数组有不同的长度,它似乎不可行!如果它总是具有相同的长度,那么它将非常适合。@PolRod确实,这适用于不同长度的数组<代码>[1,2]&[2,3,4]返回
[2]
。我理解。我的意思是,如果选项ID的数组将有2个元素,我可以执行上面的示例。但是,如果下次它将有3个元素,我将不得不添加一个新的
&Option.find(array[2])。users
。换句话说,似乎必须对
&Option.find(array[i])的数量进行硬编码。所需的用户
取决于Option\u id数组的长度。如果我错了,请纠正我,但这里的预期\u用户似乎包含对Option\u id上的任何选项做出响应的任何用户。对吗?我需要的是一个用户列表,这些用户已经回答了option_ID中的所有选项。因此,已回复1、2和5的用户不应出现在列表中,但已回复1、2、3、4和5的用户将出现在列表中。
option_ids = [1, 2, 3, 4, 5]

# select all the user_id's from the answers table (by joining options and answers tables) 
# based on the option_ids array (1 SQL Query)
user_ids = Option.joins(:answers)
                 .where('answers.option_id IN (?)', option_ids)
                 .select('answers.user_id')

# get the users from the users table (1 SQL Query)  
expected_users = User.find(user_ids)