Rails - will_paginate 说“变量似乎是空的.您是否忘记为 will_paginate 传递集合对象?" [英] Rails - will_paginate says "variable appears to be empty. Did you forget to pass the collection object for will_paginate?"
问题描述
我有这个查询:
@cars = Car.paginate(page: params[:page], per_page: 5).order(created_at: :desc).group_by { |r| r.created_at.to_date }
并在视图中:
= will_paginate @cars
但我收到此错误(在 site#index
中呈现):
But I am getting this error (rendered in site#index
):
The @site variable appears to be empty. Did you forget to pass the collection object for will_paginate?
我也尝试以这种方式更新查询:
I've also tried to update the query this way:
@cars = Car.order(created_at: :desc).paginate(page: params[:page], per_page: 5).group_by { |r| r.created_at.to_date }
但是错误还是一样.
如何解决这个问题?
谢谢
推荐答案
您可以在控制器中执行以下操作:
You can do something like this in your controller:
@car_paginator = Car.paginate(page: params[:page], per_page: 5).order(created_at: :desc)
@cars = @car_paginator.group_by { |r| r.created_at.to_date }
然后在您的视图中更改带有分页的行:
Then change the line with the pagination in your view:
= will_paginate @car_paginator
问题是:当你使用 paginate
方法时,结果不是一个普通的数组或数据库关系,而是一个包含一些额外信息的对象,比如 @size
.如果您在其上运行 group_by
,您将删除额外的属性并返回一个普通的哈希值.
The problem is: When you use the paginate
method the results is not a normal array or database relation but an object that has some extra information like @size
. If you run group_by
on that you remove that extra attributes and return a plain hash.
这篇关于Rails - will_paginate 说“变量似乎是空的.您是否忘记为 will_paginate 传递集合对象?"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!