简体   繁体   中英

Access deep nested objects in Rails

In my Rails app I have Users, Roles, and Permissions.

The associations are as follows:

class User < ActiveRecord::Base
  has_and_belongs_to_many :roles, :join_table => 'users_roles'
end

class Role < ActiveRecord::Base
  has_and_belongs_to_many :users, :join_table => 'users_roles'
  has_and_belongs_to_many :permissions, :join_table => 'roles_permissions'
end

class Permission < ActiveRecord::Base
  has_and_belongs_to_many :roles, :join_table => 'roles_permissions'
end

When listing permissions I want to get the count of roles and users for that permission.

I can do:

<% @permissions.each do |permission| %>
    <%= permission.roles.count %>
<% end %>

But if I do:

<% @permissions.each do |permission| %>
    <%= permission.roles.users.count %>
<% end %>

I get an error that users is undefined!

In my controller I have:

@permissions = Permission.includes(roles: :users)

So should be pulling through the users as well...

This cannot work because your "permission.roles" is an array (or more exactly a Relation), there is no "users" method defined.

Without having it tested, but it should work:

You could add a users relation to permission with ":through => :roles" and then just call permission.users.count

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM