Rails二阶关联过滤

时间:2019-03-29 09:49:04

标签: ruby-on-rails ruby ruby-on-rails-4 activerecord

我有一些模型,如下所示:

class Examinee < ActiveRecord::Base
  has_many :activities, as: :invoker
  has_many :tests

  def get_location
    t = self.tests.last
    l = nil
    if t.blank?
      a = self.activities.last
      l = a.location unless a.blank?
    else
      l = t.location
    end
    l
  end
end

class Test < ActiveRecord::Base
  belongs_to :user
  belongs_to :examinee
  has_many :activities, as: :invoker
  delegate :location, to: :user
end

class User < ActiveRecord::Base
  belongs_to :location
  has_many :tests
end

class Location < ActiveRecord::Base
  has_many :activities
  has_many :users
  has_many :tests, through: :users
end

class Activity < ActiveRecord::Base
  belongs_to :invoker, polymorphic: true
  belongs_to :location
end

现在,在examinee方法中定义了将location与它的正确get_location关联的逻辑。

由于我需要将考生与他们相关的location一起列出,因此我目前在examinees索引中所做的是:

def index
  @examinees = Examinee.preload(:activities, :tests).references(:locations).order(created_at: :desc)
end

一个新的客户请求已提出:按位置过滤此列表。自然,我尝试了where的所有变体:

@examinees.where(location_id: 2)
@examinees.where(location: {id: 2})
Examinee.preload(activities: :location, tests: :location).where(location_id: 2)

以及这些的更多变体。什么都没有。这里有人有过这种二阶关联过滤的经验吗?

编辑: 我可以使用以下查询:

Examinee.joins(:activities, tests: :user).where(users: {location_id: 2})
Examinee.joins(:activities, tests: :user).where(activities: {location_id: 2})

但是我需要它们的析取(或结果),这不适用于Rails 4。

0 个答案:

没有答案