在以下情况下,是否可以为多态模型创建一个作用域?
我有一个叫做突变的多态模型。

class Mutation < ApplicationRecord
    belongs_to :mutationable, :polymorphic => true
end

一个突变既属于时间登记模型,也属于疾病登记模型。时间注册和病假注册(可变)属于用户。
class SickRegistration < ApplicationRecord
  belongs_to :user
  has_many :mutations, as: :mutationable
end

class TimeRegistration < ApplicationRecord
  belongs_to :user
  has_many :mutations, as: :mutationable
end

我想为变异创建一个作用域,这样我就可以通过给定的用户名检索一组变异我在变异模型上已经有了更多的作用域,所以这个作用域必须与其他使用的作用域(用于过滤)相连接。
在突变模型上是这样的:
 scope :with_name, -> (name) { joins(mutationable: :user).where('users.name = ?', name) }

这行不通。我还尝试过在变异模型上进行委托,并在可变异模型上创建带有多个连接的自定义sql查询,但没有成功。我认为一定有一种(更简单的)方法来解决这个问题,但我找不到任何好的例子或答案。
请帮忙。提前谢谢!

最佳答案

******试试这个*****
突变.rb

belongs_to :sick_registation, ->{where(mutations: {mutationable_type: 'SickRegistation'})},
foreign_key: 'mutationable_id'

belongs_to :time_registation, ->{where(mutations: {mutationable_type: 'TimeRegistation'})},
foreign_key: 'mutationable_id'

scope :with_name, ->(name){
  joins(sick_registation: :user).where(user:{name: name}) +
  joins(time_registation: :user).where(user:{name: name})
}

说明:
多态关系和用户之间没有直接关系。
所以,我加入了个人相关的结果,即生病和时间。

关于ruby-on-rails - Ruby on Rails中的多态模型的范围,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46691022/

10-12 12:51
查看更多