2011-08-11 56 views
0

什么是最好的方式来了解当前选择ID是否已经是Datamapper结果的一部分,而无需遍历所有结果并构建数组?Datamapper - 结果集中是否包含id

@saved_item = Array.new 
    current_user.items.all.each do |item| 
      @saved_items.push(item.id) 
    end 

    if (@saved_items.include?(selection.id)) 
      true 
    else 
      false 
    end 

回答

1

current_user.items.detect { |i| i.id == selection.id }将返回指示选择ID是否包含在current_user.items收集一个布尔(真/假)。

+1

嗯我很确定#detect将返回一个具有给定ID的项目。我会建议使用#any?而是像这样: current_user.items.all.any? {| i | i.id == selection.id} – solnic

+0

solnic是对的:'#detect'返回给定块返回true的第一个实例,或者如果集合中没有任何实例执行,则返回nil。 –

0

current_user.items.delete(selection.id)

这也可以使用,这将在数组中返回选择ID是否存在其他将返回零。

相关问题