views:

144

answers:

2

I've got users who are members of groups through a membership join table, and one of the attributes of that join table is "administrator". I'm trying to do a check inside of a group's member view, looping through each member to see if they are an administrator.

In the view I tried the following:

for user in @group.users
  if user.administrator?
    ...DO STUFF
  end
end

I also tried this in the controller:

@administrators = @group.memberships.find(:all, :conditions => ["administrator = 1"])

But no luck. Any thoughts?

UPDATE - per below, put a method into the user model:

def is_administrator_of(group_id)
        Membership.find(:first, :conditions => ['user_id = ? AND group_id = ? AND administrator = ?', self[:id], group_id, true])
end
+1  A: 

Although I think you could setup associations to accomplish this I think the easiest way to do it would be to add a method to your User model that allows you to check for each user (this way it would fit in the loop you have provided). I don't know if it will drop right it, may take a few quick changes but you could start with something like:

User Model

def is_administrator_of(group_id)
    Membership.find(:first, :conditions => ['user_id = ? AND group_id = ?', self[:id], group_id]).administrator == 1
end
Rabbott
With a very small modification this worked awesome. Not sure if passing true in there is the right way to do it but it worked out great. Thanks! Membership.find(:first, :conditions => ['user_id = ? AND group_id = ? AND administrator = ?', self[:id], group_id, true])
Sean Johnson
+1  A: 

I think this would be a cleaner way to do this

class Group < ActiveRecord::Base
  has_many :memberships
  has_many :users, :through => :memberships
  has_many :admins, :through => :memberships, :source => :user,
           :conditions => ['memberships.administrator = ?', true] 
end

You now have a group.admins list

for user in @group.admins
    ...DO STUFF
end
The conditions should probably read 'memberships.administrator' as table names are pluralized.
hurikhan77
How would I reference that in the view - would I still need the is_administrator_of method? or would I be able to do something like:<% if @user.group.admin? %>
Sean Johnson
thanks for the comments, I updated the answer