Ruby:如果不在数组 B 中,如何从数组 A 中删除项目? [英] Ruby: how to remove items from array A if it's not in array B?
问题描述
我已经准备好了这两个数组:
I have prepare these two arrays:
list_of_students = Student.where('class = ?', param[:given_class])
list_of_teachers = Teacher.where(...)
Student
属于Teacher
和Teacher
拥有_many students
.
Student
belongs_to Teacher
and Teacher
has_many students
.
现在,我需要从 list_of_students
中删除所有项目(学生),其中 teacher_id
不包含在 list_of_teachers
中.
And now, I'd need to remove from the list_of_students
all items (students), where teacher_id
is not included in list_of_teachers
.
我找到了一些关于比较数组的技巧和 HOWTO,但这些都没有帮助解决这个问题.
I found some tips and HOWTO's on comparing arrays, but none of that helped to figure out this case.
提前致谢
推荐答案
您可以使用 IN
SQL 语句.
You can use the IN
SQL statement.
list_of_students = Student.where('class = ? AND teacher_id IN (?)', param[:given_class], list_of_teachers.map(&:id))
如果 list_of_teachers
是 ActiveRecord::Relation
(而不是数组),您也可以使用 #pluck(:id)
或(来自 Rails 4)#ids
If the list_of_teachers
is an ActiveRecord::Relation
(and not an array), you can also use #pluck(:id)
or (from Rails 4) #ids
Student.where('class = ? AND teacher_id IN (?)', param[:given_class], list_of_teachers.ids)
有多种编写IN
语句的方法.鉴于你已经有了一个 where
,我把它加入了主要的 where.但是你也可以写
There are several ways to write the IN
statement. Given you already have a where
, I joined it to the main where. But you could also write
Student.where('class = ?', param[:given_class]).where(teacher_id: list_of_teachers)
或
Student.where(class: param[:given_class], teacher_id: list_of_teachers)
另请注意,您不需要将教师列表分配给变量.
Also note you don't need to assign the list of teachers to a variable.
Student.where(class: param[:given_class], teacher_id: Teacher.where(...).ids)
最后但并非最不重要的一点,如果您的 Teacher
查询很简单,您可能希望使用单个查询和一个 JOIN.假设您想获取所有名为 Rose
的教师.
Last but not least, if your Teacher
query is simple, you may want to use a single query and a JOIN. Assume you want to get all the Teachers with name Rose
.
Student.where(class: param[:given_class], teacher_id: Teacher.where(name: 'Rose').ids)
您可以将相同的查询重写为
You can rewrite the same query to
Student.where(class: param[:given_class]).joins(:teacher).where(teacher: { name: 'Rose' })
or(最后一个较短的表达式)
or (the final and shorter expression)
Student.joins(:teacher).where(class: param[:given_class], teacher: { name: 'Rose' })
这篇关于Ruby:如果不在数组 B 中,如何从数组 A 中删除项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!