2017-04-06 85 views
0

我试图创建一个对象,并把布尔为true,并在任何情况下 日志显示错误后重定向。如果布尔值为真,Rails如何控制器重定向?

有人知道如何?

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 
+0

你的错误是什么? –

+0

'@ brand.save'将是一个布尔值,除非你已经做了一些产生异常的东西。 – tadman

回答

0

我不确定具体哪里有什么问题,但有一些事情并没有真正在适当的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处理程序中,您可以在其中执行一次。

您的移动电话html_safe到模板当您参考flash[:success]。在这里逃避现在还为时过早。在某些情况下,您可能会发送JSON,而您不希望它以HTML格式。