我的目标是在true或show new path的情况下将用户重定向到index path。
class PostsController < ApplicationController
before_action :check_condition, only: [:index, :new]
def check_condition
if true
redirect_to posts_path
else
redirect_to new_post_path
end
end
def index
@posts = Post.find()
end
def new
@new_post = Post.new(title: "test")
end
end当我转到索引路径或新路径时,浏览器上的错误重定向次数过多
发布于 2020-04-14 13:27:10
此时,无论您是否已经在post_path上,只要if-condition为true,就可以重定向到post_path。
您只需要重定向,除非您已经在指向预期方法的路径上。这可以通过检查当前的action_name来完成
def check_condition
if true
redirect_to posts_path unless action_name == 'index'
else
redirect_to new_post_path unless action_name == 'new'
end
end 发布于 2020-04-14 07:57:05
你正在运行一个无限循环的重定向。
您正在添加check_condition作为before_action。这意味着,每次重定向到index或new页面时,check_condition都会再次运行,而不会到达index或new方法并重新进行重定向,依此类推。
我的建议是在view或helper方法中编写条件检查器(首先确定链接的路径),而不是在controller中。
发布于 2020-04-14 14:23:21
试试这个。重定向后需要返回。
def check_condition
if true
redirect_to posts_path && return
else
redirect_to new_post_path && return
end
end https://stackoverflow.com/questions/61190364
复制相似问题