我可以在ActiveRecord中使用独立子句吗?

时间:2012-01-26 20:27:19

标签: active-record-query

我想在我的两个查询中分析出where子句,如下所示:

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

但ActiveRecord并不开心。我以为你可以独立地分解查询位。

1 个答案:

答案 0 :(得分:0)

我最终做到了这一点,虽然我仍然想知道我是否错过了另一种更好的方式:

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)