Model.models.models or model.models.find(:first).models


#1

I the following three models which all have has_and_belongs_to_many

User <-> UserGroup <-> Permissions

class UserGroup < ActiveRecord::Base
has_and_belongs_to_many :users, :join_table => “user_usergroup_join”
has_and_belongs_to_many :permissions, :join_table =>
“usergroup_permission_join”, :uniq => true

end

I can do this:

permissions = user.user_groups.find(:first).permissions

but not:

permissions = user.user_groups.permissions

I want to get all the user permissions, do I have to loop though each
user group and add the permission from each one by one?

Many thanks in advance!


#2

The problem here is that

‘user.user_groups’ returns an array of activerecord objects
You can’t use an association on an array.

Something like this may work.

user.user_groups.collect {|o| o.permissions}.flatten.uniq

Which will give you an array that contains the unique permission objects
for all entries (I think).

On Monday, April 17, 2006, at 7:29 PM, Pete wrote:

user group and add the permission from each one by one?

Many thanks in advance!


Posted via http://www.ruby-forum.com/.


Rails mailing list
removed_email_address@domain.invalid
http://lists.rubyonrails.org/mailman/listinfo/rails

_Kevin


#3

Thanks!


#4

user.user_groups.class => Array
user.user_groups.find(:all).class => Array

permissions = user.user_groups.collect {|o| o.permissions}.flatten.uniq
permissions.class => Array
permissions.find(:all) => method missing

How come I can do a find on one array, but not another?
I understand the Array class has no find and AR class does, so how does
this work?

My alternative to using find is to use ‘each’ on the array and check for
matching records, it works, but does this look correct?

def has_permission?(controller, action)
for p in self.permissions do
if p.controller == controller && p.action == action
return true
end
end
return false
end

def permissions
self.user_groups.collect {|o| o.permissions}.flatten.uniq
end