在 Rails 中遍历数组内部对象内部数组

Iterating through an array inside object inside array in Rails

我正在尝试遍历数组中对象内的数组,并让所有教师的科目匹配。这是嵌套数组 Teacher:

teachers: [
    {name: "Dave", subjects: ["english", "math"]},
    {name: "Jamal", subjects: ["history", "science"]},
    {name: "Brian", subjects: ["science", "gym"]},
    {name: "Sally", subjects: ["math", "history"]}
]

这是主题数组:

subjects: ["english", "gym"]

我希望能够找到所有拥有“英语”和“体育”科目的老师。所以基本上需要取回以下输出:

teachers: [
    {name: "Dave", subjects: ["english", "math"]}, 
    {name: "Brian", subjects: ["science", "gym"]}
]

这是我到目前为止的想法,但这只会呈现第一个包含“english”的对象,即 Dave。我意识到 return 使它退出循环,但我必须添加 return 否则会出现双渲染错误。答案很可能是一种完全不同的方式,因此我们将不胜感激!

subjects.each do |subject|
        Teacher.all.each do |teach|
          if (teach.subjects).include?(subject) then
            render json: teach and return
          end         
        end
end
teachers: [
    {name: "Dave", subjects: ["english", "math"]}
]

我怎样才能让循环也能返回 Brian?

听起来您正在寻找教授科目数组中任何科目的教师,因此:

teachers = [
    {name: "Dave", subjects: ["english", "math"]},
    {name: "Jamal", subjects: ["history", "science"]},
    {name: "Brian", subjects: ["science", "gym"]},
    {name: "Sally", subjects: ["math", "history"]}
]

subjects = ["english", "gym"]

teachers.select do |teacher|
  (subjects & teacher[:subjects]).size > 0
end

ampersane 运算符是数组元素之间的交集 - 换句话说,两个元素中的值。