0

I've written the following method to combine the References of Sections model and it's children:

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

But section.combined_references returns the following error:

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

It seems to have collected the correct values for ids, have I structured the query incorrectly?

3 Answers 3

5

Transform last line to:

Reference.where(section_id: ids)

and it should produce:

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

And you can shorten your code by one line with :

 ids = []
 ids << self.id

to

 ids = [self.id]
Sign up to request clarification or add additional context in comments.

Comments

2

it's invalid statement WHERE (section_id = 3,4) correct would be

WHERE (section_id in (3,4))

Please use:

Reference.where(:section_id => ids)

Comments

2

You can try something like this instead:

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

You can also query the database with:

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

The following has the most readability in my opinion:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.