Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/54.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如果我使用重定向到i';我会在浏览器上被重定向太多_Ruby On Rails_Ruby - Fatal编程技术网

Ruby on rails 如果我使用重定向到i';我会在浏览器上被重定向太多

Ruby on rails 如果我使用重定向到i';我会在浏览器上被重定向太多,ruby-on-rails,ruby,Ruby On Rails,Ruby,我的目标是将用户重定向到索引路径,如果为true,则显示新路径 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

我的目标是将用户重定向到
索引路径
,如果为true,则显示
新路径

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
class PostsController

当我转到“索引路径”或“新路径”时,浏览器上的错误重定向过多。对不起,要检查的条件是什么?如果用户已登录?我想你的问题可能太多了。尝试:

def check_condition
     path = condition ? posts_path : new_post_path
     redirect_to path
end 

你正在运行一个无限的重定向循环

您正在将
检查条件添加为
操作之前的
。这意味着,每当您重定向到
索引
新建
页面时,
检查条件
将再次运行,而不会到达
索引
新建
方法并再次重定向,依此类推


我的建议是在
视图
助手
方法中编写条件检查器(首先确定链接的路径),而不是在
控制器
中,每当if条件为真时,无论您是否已在
post\u路径上,都会重定向到
post\u路径

除非已经在预期方法的路径上,否则只需重定向。可通过检查电流来实现:


试试这个。您需要在重定向后返回

def check_condition
  if true
    redirect_to posts_path && return
  else
    redirect_to new_post_path && return
  end
end 

您的代码的行为与您编写代码时的行为完全相同。在
索引
新建
之前,
检查条件
将始终重定向到
索引
。在重定向到
索引
时,在调用
索引
之前,
检查条件
将重定向到
索引
。在重定向到
索引
时,在调用
索引
之前,
检查条件
将重定向到
索引
。在重定向到
索引
时,在调用
索引
之前,
检查条件
将重定向到
索引
。在重定向到
索引
时,在调用
索引
之前,
检查条件
将重定向到
索引
。您正在操作前运行
:在每个操作前检查条件
。例如,在
索引上
。我不能提出解决方案,因为我不清楚你到底想达到什么目的。只有这两种方法,为什么需要重定向?@spickermann很简单,如果条件为true,则转到index,否则转到new。我将如何实现这一点?如果有其他方法,请让我知道。这会如何改变行为?您只需使用三元运算符而不是if-else块。您只需使用一个重定向到。也许你的两个条件都在某个点上命中了……if-else的两个分支怎么能同时命中呢?那太可笑了。如果是因为方法被调用了两次,那么它也会发生在代码中。
method\u name
到底是什么?对不起,我是ruby的新手。我不知道你指的是什么,我指的是
action\u name
,这是我在回答中链接的方法。谢谢,伙计,现在我知道它为什么一直在重定向了。我需要添加
,除非
def check_condition
  if true
    redirect_to posts_path && return
  else
    redirect_to new_post_path && return
  end
end