如何在Rails 4.2.1中重用另一个关联?

时间:2016-05-16 13:02:50

标签: ruby-on-rails ruby ruby-on-rails-4 rails-activerecord

我有一个模型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

1 个答案:

答案 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上的范围。