Ruby on rails 如果布尔值为真,Rails如何重定向控制器?
我试图创建一个对象,并将布尔值转换为true,然后重定向 在任何情况下,日志都会显示错误 有人知道怎么做吗Ruby on rails 如果布尔值为真,Rails如何重定向控制器?,ruby-on-rails,ruby,ruby-on-rails-3,Ruby On Rails,Ruby,Ruby On Rails 3,我试图创建一个对象,并将布尔值转换为true,然后重定向 在任何情况下,日志都会显示错误 有人知道怎么做吗 class BrandsController < ApplicationController def new @brand = current_user.build_brand(params[:brand]) end def create @brand = current_user.build_brand(params[:brand]) i
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
class BrandsController
我不确定这里到底出了什么问题,但有些事情并没有以正确的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
class BrandsController
使用保存如果出现问题,code>将生成异常,因此您可以完全避免if
。然后,您可以通过重新呈现表单来处理无法保存的情况。您还可以将重复的代码移动到before\u action
处理程序中,在该处理程序中您可以执行一次
当您引用flash[:success]
时,将html\u safe
调用移动到模板中。在这里逃跑还为时过早。在某些情况下,您可能会改为发送JSON,而不希望它以HTML形式出现。您的错误是什么?@brand.save
将是一个布尔值,除非您执行了生成异常的操作。