【问题标题】:Ruby: how to remove items from array A if it's not in array B?Ruby:如果数组A不在数组B中,如何从数组A中删除项目?
【发布时间】:2014-11-21 13:50:22
【问题描述】:

我已经准备了这两个数组:

list_of_students = Student.where('class = ?', param[:given_class])
list_of_teachers = Teacher.where(...)

Studentbelongs_to TeacherTeacher has_many students

现在,我需要从list_of_students 中删除所有项目(学生),其中teacher_id 不包含在list_of_teachers 中。

我找到了一些关于比较数组的技巧和 HOWTO,但这些都没有帮助解决这个问题。

提前谢谢你

【问题讨论】:

    标签: ruby-on-rails ruby rails-activerecord


    【解决方案1】:

    您可以使用IN SQL 语句。

    list_of_students = Student.where('class = ? AND teacher_id IN (?)', param[:given_class], list_of_teachers.map(&:id))
    

    如果list_of_teachersActiveRecord::Relation(而不是数组),您也可以使用#pluck(:id) 或(来自Rails 4)#ids

    Student.where('class = ? AND teacher_id IN (?)', param[:given_class], list_of_teachers.ids)
    

    有几种方法可以编写IN 语句。鉴于您已经有一个where,我将它加入到主要位置。但你也可以写

    Student.where('class = ?', param[:given_class]).where(teacher_id: list_of_teachers)
    

    Student.where(class: param[:given_class], teacher_id: list_of_teachers)
    

    另请注意,您不需要将教师列表分配给变量。

    Student.where(class: param[:given_class], teacher_id: Teacher.where(...).ids)
    

    最后但同样重要的是,如果您的 Teacher 查询很简单,您可能希望使用单个查询和 JOIN。假设您想获取所有名称为 Rose 的教师。

    Student.where(class: param[:given_class], teacher_id: Teacher.where(name: 'Rose').ids)
    

    您可以将相同的查询重写为

    Student.where(class: param[:given_class]).joins(:teacher).where(teacher: { name: 'Rose' })
    

    or(最后一个更短的表达式)

    Student.joins(:teacher).where(class: param[:given_class], teacher: { name: 'Rose' })
    

    【讨论】:

    • @user984621 只需确保您切换查询的顺序,因此 list_of_teachers 是第一个运行的,因为显然 Simone 在他的查询中使用了结果
    【解决方案2】:

    你可以试试

    a = [1,2,3]
    b = [1,4,5]
    
    pry(main)> a.delete_if {|a1| !b.include? a1}
    => [1]
    

    它检查 a 中的每个值是否在 b 中。如果不是,它会从 a 中删除值并最终为您提供一个数组。

    这是一个例子。您可以相应地使用它

    【讨论】:

    • 问题是关于查询的
    • @МалъСкрылевъ,OP 说我已经准备了这两个数组(它们是关系),但他正在询问如何从数组中删除它们。
    • 我认为这个问题不是关于查询,而是关于如何从第二个数组中删除,所以相应地发布了我的答案!
    猜你喜欢
    • 1970-01-01
    • 2019-01-27
    • 2019-09-06
    • 1970-01-01
    • 1970-01-01
    • 2016-10-28
    • 1970-01-01
    • 1970-01-01
    • 2021-10-19
    相关资源
    最近更新 更多