【问题标题】:Iterating over a 3 way join迭代 3 路连接
【发布时间】:2012-10-23 21:43:38
【问题描述】:
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

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

我想我可以写:

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

但这真的很难看。我认为必须以某种方式使用 join 方法,但我无法弄清楚。谢谢!

【问题讨论】:

    标签: ruby-on-rails ruby activerecord join


    【解决方案1】:

    试试:

    Cell.where(:"#{a.class.to_s.underscore}_id": a.id, :"#{b.class.to_s.underscore}_id": b.id).each do |cell|
      # your code
    end
    

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

    【讨论】:

    • (a.class.to_s.underscore+"_id").to_sym 不同但不是更好:)
    • 我更喜欢字符串插值,因此它更具可读性,并表明我们准确地创建了一个字符串。
    • 顺便说一句,Cell.select.... 和 Cell.where .... 之间有什么区别。似乎是同一个意思?
    • select用于选择列,where用于设置条件。
    猜你喜欢
    • 1970-01-01
    • 2016-11-18
    • 2017-02-12
    • 2012-12-17
    • 2013-07-02
    • 1970-01-01
    • 2015-06-16
    • 1970-01-01
    相关资源
    最近更新 更多