Rails 4 Area for HABTM Association

I'm new to rails and I created a field in the HABTM association, but I still think it looks unnatural and not elegant, so I think there should be a better way to do this. Can anyone advise me if there is such a better way? I saw other posts in which people have the same question ( Area for HABTM self-association ) without an 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) }
+4
source share
1 answer

try it. It is more optimized.

 scope :by_role,  ->(role) { joins(:roles).where(roles: { name: role }) }
+10
source

Source: https://habr.com/ru/post/1599735/


All Articles