我有以下型号:
class ServiceProvider < ActiveRecord::Base
has_many :versions, class_name: "ServiceProviderVersion"
end
class ServiceProviderVersion < ActiveRecord::Base
belongs_to :service_provider
has_many :service_provider_roles, :through => :service_provider_to_role_maps
scope :effective, -> { where("effective_date <= ?", Time.now).order('effective_date desc') }
end
class ServiceProviderToRoleMap < ActiveRecord::Base
belongs_to :service_provider_version
belongs_to :service_provider_role
end
class ServiceProviderRole < ActiveRecord::Base
validates :name, presence: true, uniqueness: true
has_many :service_provider_versions, :through => :service_provider_to_role_maps
has_many :service_provider_to_role_maps, :dependent => :destroy
end
现在我正在努力让所有有效且属于特定角色的服务提供商。理想情况下,我想做以下
ServiceProviderVersion.effective.by_role('Admin')
但是,因为ServiceProviderVersion.effective
返回的不仅仅是一条记录,我无法在ServiceProviderVersion上定义一个范围,该范围将按角色进行过滤。
有没有办法实现这个目标?我正在使用Rails4
答案 0 :(得分:0)
尝试类似:
class ServiceProviderRole < ActiveRecord::Base
scope :by_role, ->(name) { where(name: name) }
class ServiceProviderVersion < ActiveRecord::Base
scope :by_role, ->(name) { joins(:service_provider_roles).merge(ServiceProviderRole.by_role(name)) }
然后你可以打电话:
ServiceProviderVersion.effective.by_role('Admin')