0

before_filter的一个控制器中有这个:

def valid_people
  person_ids = params[:project][:person_ids]
  if person_ids.present?        
    person = current_user.people.where("id IN (?)", person_ids).to_a
    redirect_to(root_path) unless person
  end
end

第 4 行检查数组中ids的所有person_ids元素是否都包含在用户的people.

但是,如果不是这种情况,它会引发错误。

我怎样才能让第 4 行返回nil

谢谢你的帮助。

4

1 回答 1

1

检查present?blank?。这也处理空数组:

redirect_to(root_path) if person.blank?

顺便说一句:该变量person应该重命名为people,因为它为人返回一个数组,而不仅仅是一个人。

于 2013-10-27T09:13:14.397 回答