简体   繁体   English

RAB 4在HABTM协会上的范围

[英]Rails 4 scope on HABTM association

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. 我是一个铁杆新手,我在HABTM协会上创建了一个范围,但我仍然认为它看起来不自然,不优雅,所以我认为必须有一个更好的方法。 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... 我见过其他帖子,人们有同样的问题( 自我加入HABTM协会的范围 )没有回答......

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) }

try this. 尝试这个。 it is more optimized. 它更加优化。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM