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

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


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!

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

Rails mailing list
[email protected]



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
return false

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

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs