0

What's the most elegant way of knowing if the current selection ID is already part of the Datamapper results, without iterating through all of the results and building an Array?

    @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
Tom
  • 33,626
  • 31
  • 85
  • 109

2 Answers2

1

current_user.items.detect { |i| i.id == selection.id } will return a boolean (true/false) indicating whether the selection id is included in the current_user.items collection.

  • 1
    hmm I'm pretty sure #detect will return an item with the given id. I'd suggest using #any? instead like this: current_user.items.all.any? { |i| i.id == selection.id } – solnic Aug 11 '11 at 20:40
  • solnic is right: `#detect` returns the first instance for which the given block returns true, or nil if none of the instances in the collection do. – Emmanuel Gomez Aug 15 '11 at 18:01
0

current_user.items.delete(selection.id)

this also you can use which will return the selection id from the array if presence else would return nil.