Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/55.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Rails:Concat使用两种不同型号的两个CollectionProxy_Ruby On Rails_Ruby_Activerecord - Fatal编程技术网

Ruby on rails Rails:Concat使用两种不同型号的两个CollectionProxy

Ruby on rails Rails:Concat使用两种不同型号的两个CollectionProxy,ruby-on-rails,ruby,activerecord,Ruby On Rails,Ruby,Activerecord,正如标题所解释的,假设我有两个ActiveRecord::基本模型:SatStudentAnswer和ActStudentAnswer 我有一个学生模型 has_many :act_student_answers has_many :sat_student_answers 我想创建一个集合代理,将它们连接在一起,这样我就可以一起查询所有学生的答案 student.sat_student_answers.concat(student.act_student_answers) 但是我得到了一个

正如标题所解释的,假设我有两个ActiveRecord::基本模型:SatStudentAnswer和ActStudentAnswer

我有一个学生模型

has_many :act_student_answers
has_many :sat_student_answers
我想创建一个集合代理,将它们连接在一起,这样我就可以一起查询所有学生的答案

student.sat_student_answers.concat(student.act_student_answers)
但是我得到了一个
ActiveRecord::AssociationTypeMismatch:SatStudentAnswer(#70111600189260)应为,Get-ActStudentAnswer(#70111589566060)
错误

是否有方法创建具有两种不同模型的集合代理,以便我可以继续使用活动记录查询界面?如果没有,解决这个问题的最佳方法是什么


谢谢你的帮助

你可以这样做

array = student.sat_student_answers + student.act_student_answers
那么比如说

array.each {|item| p item.student}

看起来您实际上希望这两个模型只是一个模型,分为两类
act
sat

class Student < ActiveRecord::Base
  # ...
  has_many :answers
  # ...
end

class Answer < ActiveRecord::Base
  # ...
  scope :act, -> { where kind: :act }
  scope :sat, -> { where kind: :sat }
  # ...
end
student.answers.act.concat student.answers.sat
# that is similar to
student.answers.act << student.answers.sat
但是,
concat
方法将记录添加到接收关联中,如果关联的所有者被持久化,则将其保存在数据库中。我真的不知道你想在那里做什么。您是否将ACT答案与SAT答案混合,使SAT答案包含ACT答案

见:

您可能想要的是:

student.answers
# or
act_and_sat_answers = student.answers.where(kind: [:act, :sat])

# chain more filter query
act_and_sat_answers.where(correct: true) 

如果您真的想使用两种不同的模型,那么您必须创建自己的集合代理。

据我所知,没有方法创建Rails AR:与其中不同模型的关系(我在本期中挖掘了我需要创建具有不同类型帖子的新闻提要时)。我的解决方案不是很漂亮,但很有效:我用多态创建了更多的模型。您可以查询这些新定义模型的集合,并按字段答案类型区分sat答案和act答案。

这不是我要找的。如问题中所述,我仍然希望它是一个CollectionProxy(而不是ruby数组),这样我就可以使用Active Record查询接口。