Forum: Ruby on Rails delete_if does not work on associations

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
(Guest)
on 2009-02-05 11:33
(Received via mailing list)
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
Frederick C. (Guest)
on 2009-02-05 11:39
(Received via mailing list)
On Feb 4, 11:33 pm, "removed_email_address@domain.invalid"
<removed_email_address@domain.invalid> wrote:
> 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
(Guest)
on 2009-02-05 20:57
(Received via mailing list)
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
This topic is locked and can not be replied to.