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

On 5 Feb., 04:38, Frederick Cheung <[email protected]> wrote:
> On Feb 4, 11:33 pm, "[email protected]"
>
> <[email protected]> wrote:
> > 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
>
>
>
> > 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
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to 
[email protected]
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to