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 –

On Sun, 20 Aug 2006, Daniel H. wrote:

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


http://www.rubypowerandlight.com => Ruby/Rails training & consultancy
----> SEE SPECIAL DEAL FOR RUBY/RAILS USERS GROUPS! <-----
http://dablog.rubypal.com => D[avid ]A[. ]B[lack’s][ Web]log
Ruby for Rails => book, Ruby for Rails
http://www.rubycentral.org => Ruby Central, Inc.

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 –

On Sun, 20 Aug 2006, Daniel H. wrote:

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

OK… then don’t do what I suggested in my last post :slight_smile: I thought
you wanted pop to actually delete the association.

David


http://www.rubypowerandlight.com => Ruby/Rails training & consultancy
----> SEE SPECIAL DEAL FOR RUBY/RAILS USERS GROUPS! <-----
http://dablog.rubypal.com => D[avid ]A[. ]B[lack’s][ Web]log
Ruby for Rails => book, Ruby for Rails
http://www.rubycentral.org => Ruby Central, Inc.

Hi –

On Sun, 20 Aug 2006, Daniel H. wrote:

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

David


http://www.rubypowerandlight.com => Ruby/Rails training & consultancy
----> SEE SPECIAL DEAL FOR RUBY/RAILS USERS GROUPS! <-----
http://dablog.rubypal.com => D[avid ]A[. ]B[lack’s][ Web]log
Ruby for Rails => book, Ruby for Rails
http://www.rubycentral.org => Ruby Central, Inc.