@article.article_groups.delete_if... Dosn't work!

If I try:

      @article.article_groups.delete_if {|x|         x.group_id == x.group_id       }

It does nothing.

If I try:

      articletmp.article_groups.each{ |x|               @article.article_groups.delete(y) }

It deletes some of the groups.

@article.article_groups.clear works.

Why dosn't the to first examples work as expected??

Do I have to put groups I don't want to be deleted inn as hidden fields in my form? (I of course dosn't want every groups to be deleted as in the example above).

- Henrik

Henrik Ormåsen wrote:

If I try:

      @article.article_groups.delete_if {|x|         x.group_id == x.group_id       }

It does nothing.

If I try:

      articletmp.article_groups.each{ |x|               @article.article_groups.delete(y) }

It deletes some of the groups.

@article.article_groups.clear works.

Why dosn't the to first examples work as expected??

article_groups is an AssociationCollection, for which all the usual array methods work. But only some of these methods like delete and clear have database side-effects. The rest operate only on the in-memory array object.

So to make delete_if work on the database objects you either have to write

@article.article_groups.delete(    @article.article_groups.select {|x| x.group_id == x.group_id} )

or

@article.article_groups.each do |x|    @article.article_groups.delete(x) if x.group_id == x.group_id end

or put the following in environment.rb

class ActiveRecord::Associations::AssociationCollection    def delete_if(&block)      delete( select(&block) )    end end