Discussion Forums
- Topic List
- Most Recent Posts
- Sign In for more options
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
thanks Grant and Fernando!
