Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Rails Array#add_condition Method

DZone's Guide to

Rails Array#add_condition Method

·
Free Resource
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:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}