views:

42

answers:

1

In my application I have groups which are essentially just tags that can be assigned to different models, through a polymorphic relationship. In model Group I have:

def get_members_of(klass)
  self.group_memberships.delete_if {|gm| gm.groupable_type != klass}.map{|g| g.groupable}
end

So if I did:

group.group_memberships

I would get all the objects in group group. However, if I want to limit it to only objects that are instances of model A I would do:

group.get_members_of(A)

In the console this works exactly as it should. However, I get some unexpected behaviour within my controller:

def show
  params[:studies1] = @group.get_members_of('Study').length
  @studies = @group.get_members_of('Study')
  params[:studies2] = @studies.length
  @studies = @group.group_memberships.delete_if {|gm| gm.groupable_type != "Study"}.map{|g| g.groupable}
  params[:studies3] = @studies.length
end

As expected params[:studies1] == 1, but studies2 and 3 are == 0. I'm sure I'm missing some small thing...

A: 

The get_members_of function is deeply flawed! When get_members_of is called it removes all other members from group.group_memberships that are not of klass. When the function is called additional times for other "klasses", there are no group_members left...

This works, but looks poor:

  def get_members_of(klass)
    x = []
    self.group_memberships.each {|gm| x << gm if gm.groupable_type == klass }
    x.map{|g| g.groupable}
  end
LDK
Omar Qureshi
LDK
It is Symbol#to_proc
Omar Qureshi