验证失败后,在URL中替换防止/新操作

时间:2014-07-12 20:37:40

标签: ruby-on-rails ruby-on-rails-4

验证失败后,我希望用户的浏览器在URL中显示/ new操作而不是/ create操作(在每次验证失败后替换/ new)。有没有办法用rails做到这一点?

def new
  @user = User.new
end


def create
   @user = User.new(params[:user])

   if @user.save
     redirect_to success_path
   else
     render 'new'
   end
end

1 个答案:

答案 0 :(得分:2)

您可以使用会话重定向:

def new
  if session[:new_user_params].present?
    @user = User.new(session[:new_user_params])
    @user.valid?
  else
    @user = User.new
  end
end

def create
  @user = User.new(params[:user])

  if @user.save
    session.delete(:new_user_params)
    redirect_to success_path
  else
    session[:new_user_params] = params[:user]
    redirect_to action: :new
  end
end