删除第2页上的最后一条记录时,将用户导航回第1页
我在我的rails应用程序上使用Kaminari Gem。删除第2页上的最后一条记录时,将用户导航回第1页
我有当前的索引页面和正确的导航菜单。
def index
@dogs = Dog.all.page(params[:page]).per(20)
end
def destroy
if @dog.destroy
# use this so that if the page got other records, the user got to stay at that navigated page.
redirect_back fallback_location: dogs_path, flash: { success: 'deleted dog from list' }
else
# show some errors
end
end
当用户在第2页和删除21狗的记录,记录删除了,而浏览器显示没有记录一个空白页导致URL被指定/dogs?page=2
。
这是默认行为还是Kaminari,或者我的方法有问题?由于当前页面不包含任何记录,因此我期待Kaminari将用户重定向到1页面。
谢谢。
考虑你的狗索引页路径dogs_path
def destroy
if @dog.destroy
page = params[:page]
#this is to check if we have more elements on the page or not
@dogs = Dog.all.page(page).per(20)
if @dogs.length == 0
page = (page - 1) > 1 ? page - 1 : 1
end
redirect_to dogs_path(page: page)
else
# show some errors
end
end
您需要在完成删除操作后定义索引URL。我相信你已经完成了下面的内容。
redirect_to :back
它仍然在同一页上。
而不是后面,您应该使用索引页的URL。
我希望用户保持在同一页分页时,仍有上班驳记录cular页面。例如,想象一下导航到第25页并删除该页面上的第一条记录。然后用户得到重定向回第一页,他不得不再次浏览25页删除其他记录。 – user3920567
通常,在Rails 5中,您现在可以使用redirect_back(the_path_that_you_want)
我正在考虑这样做,但仍然在空白时重定向到相同的页面。嗯..
def delete
...
prev_page = Dogs.page(params[:page]).per(20).count < 1 ? params[:page].to_i - 1 : params[:page]
redirect_back(fallback_location: dogs_path(page: prev_page, notice: "...", anchor: "if_you_wanted_to"))
end
您可以使用下面request.referer的样品破坏,首先你保存会话引荐[:的return_to] = request.referrer,然后销毁后,您返回到上一个页面使用redirect_to会议.delete(:的return_to)
def destroy
session[:return_to] = request.referrer
....
@dog.destroy
if session[:return_to]
redirect_to session.delete(:return_to)
else
redirect_to dogs_path
end
end
谢谢!这个答案最接近我想要的行为。不知道为什么Kaminari Gem不会为我们从图书馆中做到这一点。可能是因为它在重定向之前需要对数据库进行另一个查询... – user3920567