# @article.article\_groups.delete\_if... Dosn't work!

**URL:** <https://www.ruby-forum.com/t/article-article-groups-delete-if-dosnt-work/69907>\
**Category:** Rails\
**Created:** [September 25, 2006, 2:34pm UTC](https://www.ruby-forum.com/t/article-article-groups-delete-if-dosnt-work/69907 "2006-09-25T14:34:12Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Henrik\_SSiso-8859-1](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/h/3be4f8/32.png) [@Henrik\_SSiso-8859-1](https://www.ruby-forum.com/u/Henrik_SSiso-8859-1)\
**Post date:** [September 25, 2006, 2:34pm UTC](https://www.ruby-forum.com/t/article-article-groups-delete-if-dosnt-work/69907/1 "2006-09-25T14:34:12Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![Henrik\_SSiso-8859-1](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/h/3be4f8/32.png) [@Henrik\_SSiso-8859-1](https://www.ruby-forum.com/u/Henrik_SSiso-8859-1)\
**Post date:** [September 26, 2006, 1:32pm UTC](https://www.ruby-forum.com/t/article-article-groups-delete-if-dosnt-work/69907/2 "2006-09-26T13:32:38Z")

</div>

Henrik Ormåsen wrote:

> ```
> 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

–  
We develop, watch us RoR, in numbers too big to ignore.
