Welcome to Working With Rails

 

Discussion Forums

Discuss all things Ruby on Rails with perhaps the web's most vibrant group of Ruby on Rails enthusiasts.
through association for HABTM
4 Posts
through association for HABTM

I have a question for some experts, as I was searching forums but have not found anything. I have the following relations, HABTM type:

class User < ActiveRecord::Base has_and_belongs_to_many :roles ... end

class Rol < ActiveRecord::Base has_and_belongs_to_many :permisos has_and_belongs_to_many :users ... end

class Permiso < ActiveRecord::Base has_and_belongs_to_many :roles ...
end

Someone knows how to efficiently obtain the permissions associated with a user? For example:

@user = User.find(1)

@user.permisos

This is somewhat similar to a :through association, but for HABTM, as I understand it is not supported for this type of association.

I Will appreciate any help. thanks Juan Carlos

Hi Juan,

It might help if you said a bit more about the relationships you're modeling. It sounds like a User can act in multiple Rols in your system, and each Rol grants multiple Permisos, correct? Is there a particular reason to use HABTM in your application?

An alternative approach would be to use the newer has_many :through:

class User< ActiveRecord::Base has_many :rols has_many :permisos, :through => :rols end

class Rol < ActiveRecord::Base belongs_to :user has_many :permisos end

class Permiso < ActiveRecord::Base belongs_to :rol end

In this way, you're using the Rol model as a join table between users and permisos.

Hi J.C!,

What Grant says is OK.

Alternatively, if you need to keep the HABTM relationship, you can use a proxy, as follows:

class Permiso < ActiveRecord::Base
    
  has_and_belongs_to_many :roles
 
  named_scope :in_user, lambda{ |user|
    {
    :joins      => :roles,
    :conditions => {:roles => {:id => user.rol_ids}},
    :select     => "DISTINCT `permisos`.*" 
    }
  }
 
end
class User < ActiveRecord::Base
  
  has_and_belongs_to_many :roles

  def permisos
    Permiso.in_user(self)
  end
  
end

class Rol < ActiveRecord::Base

 #no changes
 has_and_belongs_to_many :permisos
 has_and_belongs_to_many :users
 
end

That's all:


  @user.permisos # =>return all permissions objects

For more information you can see this "Alex Reisner's post":http://code.alexreisner.com/articles/has-many-through-habtm.html

Person
Forum Rating: 100
Sign In To Rate Post

thanks Grant and Fernando!

4 Posts
Login to add your message