Forum: Ruby on Rails model.models.models or model.models.find(:first).models

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Pete (Guest)
on 2006-04-17 21:29
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!
Kevin O. (Guest)
on 2006-04-17 21:49
(Received via mailing list)
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
pete (Guest)
on 2006-04-20 14:55
Thanks!
Pete (Guest)
on 2006-04-21 14:31
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
This topic is locked and can not be replied to.