问题
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