Can I have a standalone clause in ActiveRecord?

98 views Asked by At

I want to factor out the where clause in my two queries like this:

where_clause = where("(created_at >= ? and created_at < ?) or (updated_at >= ? and updated_at < ?)", range_start_date, range_end_date, range_start_date, range_end_date)
@book_instances = BookInstance.limit(pagination.items_per_page).
    offset((pagination.page - 1) * pagination.items_per_page).
    where_clause.
    order(:id)
@pagination.total_items = BookInstance.where_clause.count

But ActiveRecord is not happy. I thought you could break out the query bits independently.

1

There are 1 answers

0
Purplejacket On

I ended up doing this, though I'm still wondering if I'm missing another nicer way:

book_instances_in_date_range = BookInstance.where(
    "(created_at >= ? and created_at < ?) or (updated_at >= ? and updated_at < ?)",
    range_start_date, range_end_date, range_start_date, range_end_date)

@pagination.total_items = book_instances_in_date_range.count

@book_instances = book_instances_in_date_range.limit(pagination.items_per_page).
    offset((pagination.page - 1) * pagination.items_per_page).
    order(:id)