0

モデルとその子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 の正しい値が収集されたようですが、クエリの構造が間違っていますか?

4

3 に答える 3

5

最後の行を次のように変換します。

Reference.where(section_id: ids)

そして、それは以下を生成するはずです:

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

そして、次のようにしてコードを 1 行短縮できます。

 ids = []
 ids << self.id

 ids = [self.id]
于 2013-04-06T09:37:04.617 に答える
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 に答える
2

それは無効なステートメントです WHERE (section_id = 3,4) 正しいのは

WHERE (section_id in (3,4))

使ってください:

Reference.where(:section_id => ids)
于 2013-04-06T09:37:35.373 に答える