使用 Rails 4 创建作用域关系

Create scoped relationship with Rails 4

我在 Rails 中有两个模型:

class User < ActiveRecord::Base
    enum user_type: [:admin, :normal] 
end

class Department < ActiveRecord::Base
end

包容我写了以下Rspec测试:

require 'rails_helper'

RSpec.describe User, :type => :model do
    it { should belong_to(:department).conditions(user_type: :admin)}
end

我需要但我不知道如何实现它。如何根据类型创建两个模型之间的关系?

换句话说,如何只与 "admin" 类型的用户建立这种关系?

我看到的link或类似的问题,对我不起作用,测试仍然失败

您可以像这样使用 scope

class User < ActiveRecord::Base
  enum user_type: [:admin, :normal]
  belongs_to :department, -> { joins(:users).where("users.user_type = ?", 0) }
end

Associations are built from Relations,您可以使用 Relation 语法来自定义它们。在 -> { ... } 块中,您可以使用所有常用的 Relation 方法。