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