0

I am generating the condition for an ActiveRecord where as follows:

  query = {:status => status}

  if (limit)
    query[:limit] = @vals['limit'].to_i
  end

  if (offset && limit)
    query[:offset] = (offset - 1) * limit
  end

  rows = Review.all(query)

This works just fine. I filter on 'status' of a review and I fill in limit and offset if passed in. Problem is now that I need to add a check for 'not null' on the reviews content field. I.E. AND review.content != '' && review.content != nil

I have read you can do something like

Review.were("review <> ''")

Which by itself works but I am not sure how to incorporate that into my above command. Or change the above command to work with a where statement rather than an 'all' statement.

1
  • Try this Review.where(query).where(("review <> ''")
    – Amar
    Mar 23, 2013 at 19:02

1 Answer 1

2

I would write that code something like

query = Review.where("status = ?", status).where("review <> '' AND review IS NOT NULL")

if limit.present?
  query = query.limit(limit) 
  if offset.present?
    query = query.offset((offset - 1) * limit)
  end
end

rows = query.all

rails query object does lazy evaluation, so you can build up the query, no sql is issued to the database until you begin to iterate over the rows

alternate to .where("review <> '' AND review IS NOT NULL")

.where("COALESCE(review, '') <> ''")

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.