繁体   English   中英

带有嵌套属性的Rails 4 Filter模型多次

[英]Rails 4 Filter model multiple times with nested attributes

我有三种主要模型可以处理这种情况。 简而言之,他们之间的关系是这样的:

class Person < ActiveRecord::Base
  has_many :sessions, dependent: :delete_all, inverse_of: :person
  has_many :answers, through: :sessions
end

class Session < ActiveRecord::Base
  belongs_to :person, inverse_of: :sessions
  has_many :answers
end

class Answer < ActiveRecord::Base
  belongs_to :session
end

简而言之,着重于问题,我将总结模型的属性,而仅着眼于Answer模型的属性,因为它们是我唯一需要做的事情。 答案模型具有以下属性:

# == Schema Information
#
# Table name: answers 
#
#  id                 :integer          not null, primary key
#  session_id         :integer
#  question_option_id :integer
#  created_at         :datetime         not null
#  updated_at         :datetime         not null
#

我想要的是根据表单提供的question_option_id值过滤人员记录,在那里用户可以选择使用一个或多个答案问题选项值进行过滤。 值的发送没有问题,但是我尝试过滤人员记录没有成功,这是我获得部分成功的最接近方法:

people = Person.all
people = people.joins(:answers).uniq.where(answers: {question_option_id: some_param})

有了这个,我就能够使用一个问题选项的值进行过滤,当我尝试过滤多个问题选项时,问题就来了,它什么都不返回,这就是我尝试过的方法:

people = Person.all
people = people.joins(:answers).uniq.where(answers: {question_option_id: some_question_option_id_param})
people = people.joins(:answers).uniq.where(answers: {question_option_id: another_question_option_id_param})

问题在于,在这些条件下,查询将搜索只有一个答案且同时具有两个question_option_id值的人。 我要完成的工作是进行查询,以在他们拥有的所有答案中搜索具有这些问题选项ID的人员。 抱歉,如果我很难理解,但这是我要尝试的方法,不确定是否使用了正确的方法,欢迎提出任何建议。

这是关系分裂的情况。 对于您的情况,这样的事情就可以完成:

# question_option_ids = [some_param, some_other_param, ...]
people = Person.all
question_option_ids.each do |question_option_id|
  people = people.where('EXISTS (SELECT * FROM sessions s INNER JOIN answers a ON s.id = a.session_id WHERE s.person_id = people.id AND a.question_option_id = ?)', question_option_id)
end

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM