Rails 如果布尔值为真,如何进行控制器重定向?

Rails how to controller redirect if boolean is true?

我正在尝试创建一个对象并将布尔值转换为 true 并在之后重定向 在任何情况下,日志都会显示错误。

有人知道吗?

class BrandsController < ApplicationController

  def new
    @brand = current_user.build_brand(params[:brand])
  end

  def create
    @brand = current_user.build_brand(params[:brand])


    if @brand.save

      redirect_to "#{new_user_path}?branded=#{@current_user.branded[1]}"

flash[:success] = "thank's".html_safe
    end

  end
end

我不确定具体哪里出了问题,但有些事情并没有真正以正确的 Rails 风格完成。这是一个更传统的重做版本:

class BrandsController < ApplicationController
  before_action :build_brand, only: [ :new, :create ]

  def new
  end

  def create
    @brand.save!

    flash[:success] = "Thanks!"

    redirect_to new_user_path(branded: @current_user.branded[1])

  rescue ActiveRecord::RecordInvalid
    render(action: :new)
  end

protected
  def build_brand
    @brand = current_user.build_brand(params[:brand])
  end
end

如果出现问题,使用 save! 会生成异常,因此您可以完全避免 if。然后您可以通过重新呈现表单来处理无法保存的情况。您还可以将重复的代码移动到 before_action 处理程序中,您可以在其中执行一次。

当您引用 flash[:success] 时,将您的 html_safe 调用移动到模板中。在这里逃跑为时过早。在某些情况下,您可能会发送 JSON 而不是 HTML 形式。