collection.pop

Hi everyone,

I have a category which has_many :items, and I'm trying to use

category.items.pop

Only, the last element in items isn't being removed. Is there a way to change
this easily?

Thanks
Daniel

Right now I'm just using category.items.to_a and that works fine

Hi --

Hi everyone,

I have a category which has_many :items, and I'm trying to use

category.items.pop

Only, the last element in items isn't being removed. Is there a way to change
this easily?

If you want a pop that matches the push, you can do:

   class ActiveRecord::Associations::AssociationCollection
     def pop
       load_target
       delete(@target[-1])
     end
   end

Tested only very informally, and comes with the usual caveats about
changing default behavior.

David

Hi --

What I'm using in full is actually

def items_array
  @items_array ||= items.to_a
end

so I then have category.items_array.pop and the element is deleted

But I like your suggestion better, thanks!

Hi --

What I'm using in full is actually

def items_array
@items_array ||= items.to_a
end

so I then have category.items_array.pop and the element is deleted

But I like your suggestion better, thanks!

As long as it's clear that with my technique, you're actually changing
the database when you use 'pop'. (I imagine it is clear but I just
want to rest with an easy conscience tonight :slight_smile:

David