如果这是一个微不足道的问题,或者我对rails的理解很薄,我道歉。
我的控制器中有2个动作,索引和refine_data。
索引从数据库表中提取并显示所有数据。
refine_data使用正则表达式清除不需要的数据并返回数据的子集。
控制器看起来像:
def index
Result.paginate :per_page => 5, :page => params[:page], :order => 'created_at DESC'
end
def refine_data
results = Result.all
new_results = get_subset(results)
redirect_to :action => 'index'
end
我想使用new_results将refine_data操作重定向到同一视图(索引)。
由于new_results不是来自数据库表(或模型),我该如何构建我的paginate?
答案 0 :(得分:2)
正如我在对Sort by ranking algorithm using will-paginate的回答中所写,可以使用自定义查找方法对数据进行排序。
它可以类似地用于过滤掉不需要的数据,因为您只需要返回一组数据。通过将refine_data
的名称修改为find_refined_data
,您可以使用
Result.paginate_refined_data :per_page => 5, :page => params[:page], :order => 'created_at DESC'
在您的index
方法中。 (当然,您需要返回一组记录,而不是重定向到索引操作)
BTW 如果您可以将过滤器指定为SQL查询,也可以使用paginate_by_sql方法。这可能比抓取所有记录并对它们执行正则表达式更有效。但我觉得更复杂。
答案 1 :(得分:2)
我没有成功通过创建自己的find方法来使用will_paginate。 我几乎成功但不完全。
这是我尝试过的: 在控制器中:
def refine_data
Result.paginate_refined_data :per_page => 5, :page => params[:page], :order => 'created_at DESC', :exclude =>"somestring"
end
在模特:
def find_refined_data(args)
exclude_string = args[:exclude];
new_results = do_some_work_and_exclude_records(@results,exclude_string)
end
will_paginate在我传递一个附加参数时遇到了麻烦:排除它不理解的内容。
对我来说最简单的解决方案是创建自己的WillPaginate :: Collection对象。
所以现在我的工作方式如下:
#The method name does not cause will_paginate to intercept and try to do its magic.
def new_find_refined_data(args)
exclude_string = args[:exclude];
new_results = do_some_work_and_exclude_records(@results,exclude_string)
@entries = WillPaginate::Collection.create(1, args[:per_page]) do |pager|
# inject the result array into the paginated collection:
pager.replace(new_results)
unless pager.total_entries
# the pager didn't manage to guess the total count, do it manually
pager.total_entries = new_results.length
end
end
end
希望这可以帮助任何面临同样问题的人:
答案 2 :(得分:0)
我不确定其他答案 - 您可能希望将该方法移到模型类中。
但回答你的实际问题。 显示与另一个操作相同的视图的方法不是重定向,而是使用:
render :action => :index
答案 3 :(得分:0)
另一种替代方法可能是为您的精炼结果集创建一个named_scope。 你能将“get_subset”业务逻辑制定成数据库式命令吗?
如果是这样,您可以将finder重建为named_scope(具有这些条件) 例如:
named_scope :blue_things, :conditions => {:colour => 'blue'}
然后只需调用paginate:
Result.blue_things.paginate :per_page => 5, :page => params[:page]