【问题标题】:Rails 4 scope on HABTM associationHABTM 协会的 Rails 4 范围
【发布时间】:2015-10-16 18:53:24
【问题描述】:

我是一个 Rails 新手,我在 HABTM 协会上创建了一个范围,但我仍然认为它看起来不自然,不优雅,所以我认为必须有更好的方法来做到这一点。如果有更好的方法,谁能告诉我?我看过其他帖子,人们有同样的问题 (Scope for Self-joining HABTM Association) 却没有答案...

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

【问题讨论】:

标签: ruby-on-rails scope has-and-belongs-to-many


【解决方案1】:

试试这个。它更加优化。

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

【讨论】:

  • 谢谢,现在看起来很优雅。
猜你喜欢
  • 2012-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-07
  • 1970-01-01
  • 1970-01-01
  • 2016-07-11
相关资源
最近更新 更多