0

我编写了以下方法来结合模型及其子模型ReferencesSections

def combined_references
    ids = []
    ids << self.id
    self.children.each do |child|
      ids << child.id
    end
    Reference.where("section_id = ?", ids)
  end

section.combined_references返回以下错误:

Mysql2::Error: Operand should contain 1 column(s): SELECT `references`.* FROM `references`  WHERE (section_id = 3,4)

似乎已经收集了正确的 id 值,我是否错误地构造了查询?

4

3 回答 3

5

将最后一行转换为:

Reference.where(section_id: ids)

它应该产生:

SELECT `references`.* FROM `references`  WHERE section_id IN (3,4)

您可以将代码缩短一行:

 ids = []
 ids << self.id

 ids = [self.id]
于 2013-04-06T09:37:04.617 回答
2

这是无效的声明 WHERE (section_id = 3,4) 正确的是

WHERE (section_id in (3,4))

请用:

Reference.where(:section_id => ids)
于 2013-04-06T09:37:35.373 回答
2

您可以尝试这样的事情:

def combined_references
  ids = self.children.map(&:id).push(self.id)
  Reference.where(section_id: ids)
end

您还可以使用以下命令查询数据库:

Reference.where("section_id in (?)", ids)

以下是我认为最具可读性的内容:

def combined_references
  Reference.where(section_id: self_and_children_ids)
end

private

def self_and_children_ids
  self.children.map(&:id).push(self.id)
end
于 2013-04-06T10:02:15.790 回答