相关疑难解决方法(0)

redirect_to!=返回

我正在寻找关于行为的一些澄清redirect_to.

我有这个代码:

if some_condition
   redirect_to(path_one)
end

redirect_to(path_two)
Run Code Online (Sandbox Code Playgroud)

如果some_condition == true我收到此错误:

在此操作中多次调用渲染和/或重定向.请注意,您只能调用渲染或重定向,每次操作最多一次.

似乎该方法在redirect_to调用后继续执行.我需要编写这样的代码:

if some_condition
   redirect_to(path_one)
   return
end

redirect_to(path_two)
Run Code Online (Sandbox Code Playgroud)

ruby-on-rails

61
推荐指数
3
解决办法
2万
查看次数

使用redirect_to后如何停止控制器执行?(使用Rails)

我有一个控制器,其中包含多个操作:year和:month作为URL中的属性.我已经创建了一个私有方法check_date来检查日期是否有效,并检查日期是否在将来.

def check_date(year, month)
  if month < 1 || month > 12 || year < 2000
    flash[:notice] = I18n.t 'archive.invalid_date'
    redirect_to :action => 'index'
  elsif year > Date.today.year || (year == Date.today.year && month > Date.today.month)
    flash[:notice] = I18n.t 'archive.no_future'
    redirect_to :action => 'month_index', 
      :year => Date.today.year, 
      :month => Date.today.month,
      :type => params[:type]
  end
end
Run Code Online (Sandbox Code Playgroud)

在redirect_to之后是否存在结束控制器执行的轨道方式?

我能想到的方法是在redirect_to之后抛出一个异常,或者从check_date返回一个值并在每个调用它的动作中检查它 - 比如

def month_index 
  year = params[:year].to_i
  month = params[:month].to_i
  if !check_date(year, month)
    return
  ...
end
Run Code Online (Sandbox Code Playgroud)

但我想知道是否有一些很好的轨道方式来做到这一点.我一半希望调用redirect_to rails会认出我想要停止,但这似乎不会发生.

error-handling ruby-on-rails

44
推荐指数
4
解决办法
3万
查看次数

Redirect_to并使用return进行渲染

 def confirm_invite_new_tutor
    redirect_with_msg = false
    @game_school = GameSchool.find(params[:id])
    existing_user_emails = params[:all_emails][:existing_user] || []
    new_users = params[:param_game_school][:game_school_invites_attributes]

if existing_user_emails.present?
      existing_user_emails.each do |existing_user|
        // some code
      end
      redirect_with_msg = true
    end
    if new_users.present? 
      if @game_school.update_attributes(params[:param_game_school])
        redirect_with_msg = true
      else
         render :invite_tutor_form
      end
    end
    if redirect_with_msg 
      redirect_to @game_school, notice: "daw"
     else
      redirect_to @game_school 
    end
  end
Run Code Online (Sandbox Code Playgroud)

如果我正在执行此操作,我会收到错误

在此操作中多次调用渲染和/或重定向.请注意,您只能调用渲染或重定向,每次操作最多一次.另请注意,重定向和呈现都不会终止操作的执行,因此如果要在重定向后退出操作,则需要执行类似"redirect_to(...)并返回"的操作.

如果我使用return它将我带到其他页面,甚至不显示flash msg.如何解决这个问题?

ruby-on-rails

5
推荐指数
2
解决办法
1万
查看次数

标签 统计

ruby-on-rails ×3

error-handling ×1