delete_if does not work on associations

I tried to user delete_if on an association:

class Group < ActiveRecord::Base   has_many :memberships, :dependent => :destroy   has_many :users, :through => :memberships

  ... end

This is the controller method, trying to use delete_if. Although some elements are removed (s2 < s1), the save method does not update the association.

def intersect_or_remove_group     other_group = Group.find(params[:group_id])     s1 = @group.users.size     case params[:submit]       when "Intersect"         @group.users.delete_if { |u| !other_group.users.include?(u) }       when "Remove"         @group.users.delete_if { |u| other_group.users.include?(u) }     end     s2 = @group.users.size     if s2 < s1       @group.save     end     redirect_to @group   end

If I rewrite it like this, it works just fine:

def intersect_or_remove_group     other_group = Group.find(params[:group_id])     s1 = @group.users.size     to_be_deleted = Array.new     case params[:submit]       when "Intersect"         @group.users.each { |u| to_be_deleted << u if ! other_group.users.include?(u) }       when "Remove"         @group.users.each { |u| to_be_deleted << u if other_group.users.include?(u) }     end     to_be_deleted.each { |u| @group.users.delete(u) }     s2 = @group.users.size     if s2 < s1       @group.save     end     redirect_to @group   end

Is this a bug or a feature?

Thanks for any help in advance

Regards

Alexander

I tried to user delete_if on an association:

class Group < ActiveRecord::Base has_many :memberships, :dependent => :destroy has_many :users, :through => :memberships

... end

This is the controller method, trying to use delete_if. Although some elements are removed (s2 < s1), the save method does not update the association.

Looks like delete_if just acts on the target array, not the association itself (as a slight typing saver you can pass an array to delete.

Fred

Thanks for the hint.

Probably this is a bug, because the association is not updated correctly. Unfortunately I am not advanced enough in rails to be able to provide a patch for it.

Alexander alias MrLongleg