Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/67.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/8/logging/2.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 在3路联接上迭代_Ruby On Rails_Ruby_Activerecord_Join - Fatal编程技术网

Ruby on rails 在3路联接上迭代

Ruby on rails 在3路联接上迭代,ruby-on-rails,ruby,activerecord,join,Ruby On Rails,Ruby,Activerecord,Join,我想在属于指定a和b的所有单元格实例上编写一个迭代。我知道a和b不是同一个类的实例,但我事先不知道它们是哪一个 我想我可以写: class Participant has_many :cells end class Round has_many :cells end class Question has_many :cells end class Cell belongs_to :participant belongs_to :question belongs

我想在属于指定a和b的所有单元格实例上编写一个迭代。我知道a和b不是同一个类的实例,但我事先不知道它们是哪一个

我想我可以写:

class Participant
  has_many :cells
end

class Round
  has_many :cells
end

class Question
  has_many :cells
end

class Cell
   belongs_to :participant
   belongs_to :question
   belongs_to :Round
end

a = an instance of Participant, Question or Round
b = an instance of Participant, Question or Round
但这真的很难看。我想一定有什么办法可以使用join方法,但我一直没有弄明白。谢谢

试试看:

if a.class == Participant && b.class == Question
  Cell.select(participant_id: a.id, question_id: b.id).each do 
  ... and so on

但是我很确定有更好的方法。

(a.class.to_.s.下划线+“\u id”)。to_sym不同,但不是特别好:)我更喜欢字符串插值,因此它更可读,并显示我们确实创建了字符串。顺便问一下,单元格之间的区别是什么。选择。。。。还有牢房,在哪里。。。。似乎意思相同?
select
用于选择列,而
用于设置条件。
Cell.where(:"#{a.class.to_s.underscore}_id": a.id, :"#{b.class.to_s.underscore}_id": b.id).each do |cell|
  # your code
end