ActiveRecord ::与Array#delete_at(index)等效的方法? 也许还建议另一种实现。
results = Agent.where(target_industry: target_industry)
if !target_specialty.empty?
results.map.with_index do |result, index|
unless target_specialty.include?(result.target_specialty_1) ||
target_specialty.include?(result.target_specialty_2) ||
target_specialty.include?(result.target_specialty_3)
results.delete_at(index)
end
end
end
@result = results
基本上,如果target_specialty
过滤器是POST,那么从ActiveRecord :: Relation results
WHERE target_specialty_1 / 2/3中删除/删除所有ROWS不包括Array#target_specialty。最后将@result = results
发回给视图。
答案 0 :(得分:3)
这只从数据库中提取记录,其中target_specialty_x
都不匹配target_specialty
中的任何值:
results.where.not(
target_specialty1: target_specialty,
target_specialty2: target_specialty,
target_specialty3: target_specialty
)
这样,您就不需要删除关系中的任何项目,因为它们首先不会被数据库返回。
答案 1 :(得分:0)
我会使用Array#select方法,该方法会删除列表中不会检查条件的所有项目:
results.select do |result|
target_specialty.include?(result.target_specialty_1) ||
target_specialty.include?(result.target_specialty_2) ||
target_specialty.include?(result.target_specialty_3)
end
这也会产生更清晰的代码:)