Ruby on rails 在3路联接上迭代
我想在属于指定a和b的所有单元格实例上编写一个迭代。我知道a和b不是同一个类的实例,但我事先不知道它们是哪一个 我想我可以写: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
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