2012-01-26 37 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) 
相關問題