Rails数组条件查询

时间:2013-04-06 09:31:18

标签: ruby-on-rails

我编写了以下方法来合并References Sections模型及其子项:

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值,我是否错误地构建了查询?

3 个答案:

答案 0 :(得分:5)

将最后一行转换为:

Reference.where(section_id: ids)

它应该产生:

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

您可以使用以下代码将代码缩短一行:

 ids = []
 ids << self.id

 ids = [self.id]

答案 1 :(得分:2)

这是无效的陈述     WHERE(section_id = 3,4) 正确的是

WHERE (section_id in (3,4))

请使用:

Reference.where(:section_id => ids)

答案 2 :(得分: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