Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/54.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 Rails数组条件查询_Ruby On Rails - Fatal编程技术网

Ruby on rails Rails数组条件查询

Ruby on rails Rails数组条件查询,ruby-on-rails,Ruby On Rails,我编写了以下方法来组合模型及其子项的引用: def combined_references ids = [] ids << self.id self.children.each do |child| ids << child.id end Reference.where("section_id = ?", ids) end 它似乎收集了正确的ID值,我是否构造了错误的查询?将最后一行转换为: Reference.w

我编写了以下方法来组合模型及其子项的引用:

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

它似乎收集了正确的ID值,我是否构造了错误的查询?

将最后一行转换为:

Reference.where(section_id: ids)
它应该产生:

SELECT `references`.* FROM `references`  WHERE section_id IN (3,4)
您可以使用以下命令将代码缩短一行:

 ids = []
 ids << self.id
这是无效的声明 其中,截面_id=3,4 正确的答案是

WHERE (section_id in (3,4))
请使用:

Reference.where(:section_id => ids)

您可以尝试以下方法:

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
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