如何通过属性确定多态关联的范围

时间:2019-04-04 18:20:59

标签: ruby-on-rails scope polymorphic-associations

我想基于多态关联的属性来编写作用域。

我有模特:

class Item < ApplicationRecord

  belongs_to :person, polymorphic: true

end

class Teacher < ApplicationRecord

  has_many :items, as: :person

end

class Student < ApplicationRecord

  has_many :items, as: :person

end

老师学生都具有属性名称,我想将该属性用于以下范围:

scope :by_name, ->(name) { joins(:person).where(persons: {name: name}) }

由于我不能只提及范围,有没有办法很好地限制范围?

1 个答案:

答案 0 :(得分:1)

我不知道这样做的一种真正干净的方法……虽然笨重,但应该可以工作,但是扩展性不好。希望有人能有更好的答案。

scope :by_name, ->(name) { joins("left join teachers on person_type = 'Teacher' and person_id = teachers.id")
                          .joins("left join students on person_type = 'Student' and person_id = students.id")
                          .where('teachers.name = ? OR students.name = ?', name, name) }

要处理名称数组,可以如下进行修改...

scope :by_name, ->(*name) do
  name = name.flatten
  joins("left join teachers on person_type = 'Teacher' and person_id = teachers.id")
  .joins("left join students on person_type = 'Student' and person_id = students.id")
  .where('teachers.name IN (?) OR students.name IN (?)', name, name) 
end

这将使您可以做到

item.by_name('Smith')
item.by_name('Smith', 'Jones')
item.by_name(['Smith', 'Jones'])