Search code examples
rubyactiverecordarel

Can I write this query more elegantly with AREL/ActiveRecord?


Can I write this query shorter and/or more elegantly using the AREL/ActiveRecord API?

Foo.where("(bar is not null and bar != '') or (baz is not null and baz !='')")

Solution

  • You can do an OR operator with Arel directly but the syntax isn't hugely pretty and can get a bit hard to read. Here is what it would look like in arel:

    foo  = Foo.arel_table
    Foo.where(foo[:bar].not_eq(nil).and(foo[:bar].not_eq('')).or(foo[:baz].not_eq(nil).and(foo[:baz].not_eq(''))))
    

    I'd suggest looking at the squeel gem. It gives you access to more arel functionality in active record. Your query would like like:

    Foo.where{(bar.not_eq nil) & (bar.not_eq '') | (baz.not_eq nil) & (baz.not_eq nil)}
    

    Here is the link for more info: http://erniemiller.org/projects/squeel/

    There are a few different ways you can write that in squeel, it supports a few different syntax styles so if you don't liked the one above there are alternatives.