简体   繁体   中英

Rails Array Conditions Query

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?

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]

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM