【问题标题】:How to scope polymorphic association by attribute如何按属性确定多态关联的范围
【发布时间】:2019-04-04 18:20:58
【问题描述】:

我想根据多态关联的属性编写范围。

我有模型:

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

TeacherStudent 都具有 name 属性,我想将该属性用于以下范围:

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

既然我不能只提到范围,有什么办法可以很好地确定范围吗?

【问题讨论】:

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


    【解决方案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'])
    

    【讨论】:

    • 感谢您的帮助!如果没有更好的答案,这将不得不这样做,谢谢!
    • 嗨,我刚刚在范围内发送超过 1 个名称时发现错误,例如:Item.by_name(["a","b"] 将返回:(Mysql2::Error: Operand should包含 1 列:你知道任何解决方法吗?@SteveTurczyn
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多