Through and through

I have users, groups, permissions, and volumes, with these
relationships:

  • users HABTM groups

  • groups has_many permissions

  • permissions has_many volumes

  • groups has_many volumes :through => permissions

Is there an easy way to get all the volumes a user has access to? I can
always get a list of groups, loop over it, and get the volumes, but I
was hoping for something elegant like user.groups.volumes.

Possible?

Brian A. wrote:

Is there an easy way to get all the volumes a user has access to? I can
always get a list of groups, loop over it, and get the volumes, but I
was hoping for something elegant like user.groups.volumes.

Possible?

Perhaps something like user.groups[0].volumes would work.

Brian A. wrote:

I have users, groups, permissions, and volumes, with these
relationships:

  • users HABTM groups

  • groups has_many permissions

  • permissions has_many volumes

  • groups has_many volumes :through => permissions

Is there an easy way to get all the volumes a user has access to? I can
always get a list of groups, loop over it, and get the volumes, but I
was hoping for something elegant like user.groups.volumes.

Possible?

@user.groups.map{|g| g.volumes}.flatten

OR, the DRY way:

class Users < ActiveRecord::Base
def volumes
self.groups.map{|g| g.volumes}.flatten
end

Then you can call @user.volumes.

Brian A. wrote:

Is there an easy way to get all the volumes a user has access to? I can
always get a list of groups, loop over it, and get the volumes, but I
was hoping for something elegant like user.groups.volumes.

Possible?

Maybe something like this:

@volumes = []
user.groups.each { |g| @volumes += g.volumes }

You can try to make it more efficient by first querying @groups =
user.groups.find(:all, :include => :volumes)

Although I’m not sure what the status is of eager loading of :through
relationships.

I assume you are doing something with permissions that would limit what
you could do with a volume, so you could conceivable end up with
multiple instances of a volume, each with different permissions. How
would you resolve that?

-matthew

I assume you are doing something with permissions that would limit what
you could do with a volume, so you could conceivable end up with
multiple instances of a volume, each with different permissions. How
would you resolve that?

-matthew

Fill an array with all volumes, then call uniq! to remove dupes.

Thanks for all the responses.

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