2012-01-26 55 views
0

我要分解出where子句中我的两个查询是这样的:我可以在ActiveRecord中有一个独立的子句吗?

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的不开心。我以为你可以独立地分解查询位。

+0

我能以某种方式使用一个Model.scoped方法(匿名范围)在这里?例如:http://webjazz.blogspot.com/2008/06/anonymous-scope-unknown-cousin-of-named.html – Purplejacket

回答

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) 
相关问题