我有一个模型User
。
我有以下协会:
has_many :user_schools
has_many :schools, through: :user_schools, source: :school
has_many :active_schools, -> {where(active: true)}, through: :user_schools, source: :school
如何重用:schools
来编写:active_schools
的关联,而不重复以下内容:
through: :user_schools, source: :school
答案 0 :(得分:1)
如果您只需要查询方法,只需在User
class User < ActiveRecord::Base
scope :active_schools, -> { schools.where(active: true) }
end
并像这样使用
user.active_schools
或在School
class School < ActiveRecord::Base
scope :active, -> { where(active: true) }
end
并像这样使用
user.schools.active
甚至同时执行这两项操作并使用School
范围内User
上的范围。