5

I'm a rails newbie and I created a scope on a HABTM association, but I still think it looks unnatural, not elegant, so I think there must be a better way of doing it. Could anyone advise me if there is such better way? I've seen other posts where people have the same question (Scope for Self-joining HABTM Association) with no answer...

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
end

scope :by_role, lambda { |role_name| joins('join users_roles on users.id = users_roles.user_id').
                                    joins('join roles on users_roles.role_id = roles.id').
                                    where('roles.name = ?', role_name) }
Community
  • 1
  • 1
Donato Azevedo
  • 1,378
  • 1
  • 13
  • 22
  • read this please: http://guides.rubyonrails.org/association_basics.html#choosing-between-has-many-through-and-has-and-belongs-to-many – uday Jul 26 '15 at 15:37

1 Answers1

15

try this. it is more optimized.

 scope :by_role,  ->(role) { joins(:roles).where(roles: { name: role }) }
Athar
  • 3,258
  • 1
  • 11
  • 16