Rails - will_paginate says “variable appears to be empty. Did you forget to pass the collection object for will_paginate?”

浪尽此生 提交于 2019-12-04 04:59:34

问题


I have this query:

@cars = Car.paginate(page: params[:page], per_page: 5).order(created_at: :desc).group_by { |r| r.created_at.to_date }

and in the view:

= will_paginate @cars

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 }

But the error is still the same.

How to fix this issue?

Thank you


回答1:


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

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.



来源:https://stackoverflow.com/questions/28143083/rails-will-paginate-says-variable-appears-to-be-empty-did-you-forget-to-pass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!