Over a million developers have joined DZone.

Rails Array#add_condition Method

·
Lets you add a condition to a set of ActiveRecord conditions easily like this:


  conditions = ['active = ? and type = ?', true, 2]
  conditions.add_condition ['person_id = ?', 345]



class Array
  def add_condition(condition, conjunction='and')
    if condition.is_a? Array
      if self.empty?
        (self << condition).flatten!
      else
        self[0] += " #{conjunction} " + condition.shift
        (self << condition).flatten!
      end
    elsif condition.is_a? String
      self[0] += " #{conjunction} " + condition
    else
      raise "don't know how to handle this condition type"
    end
    self
  end
end
Topics:

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}