登录后保留表单数据/通过设计注册

时间:2015-08-19 11:28:50

标签: ruby-on-rails devise

我正在开发一个使用devise进行身份验证的rails应用程序。在我的应用程序中有一个查询表单,但只有登录用户才能填写查询表单。 如果用户没有登录,他可以填写from中的数据,但是当他点击提交时我希望他被重定向到sign_up页面,在那里他可以sign_up或sign_in。一旦他这样做,我希望他被重定向回上一页并恢复他的表格数据,这样他就不需要再次填写表格了。

到目前为止,我能够实现重定向回上一页部分,但我无法保留表单数据

我的应用程序控制器的代码:

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception
  #after_filter :store_location

    after_filter :store_location

def store_location
  # store last url - this is needed for post-login redirect to whatever the user last visited.
  return unless request.get? 
  if (request.path != "/users/sign_in" &&
      request.path != "/users/sign_up" &&
      request.path != "/users/password/new" &&
      request.path != "/users/password/edit" &&
      request.path != "/users/confirmation" &&
      request.path != "/users/sign_out" &&
      !request.xhr?) # don't store ajax calls
    session[:previous_url] = request.fullpath 
  end
end

def after_sign_in_path_for(resource)
  session[:previous_url] || root_path
end

def after_sign_out_path_for(resource_or_scope)
  request.referrer
end

end

任何人都可以帮助我保留表格数据,这样他就不需要再次填写表格了。

1 个答案:

答案 0 :(得分:4)

在表单控制器的create action中,您必须检查用户是否已登录。

基本上,您想要的是,如果用户未连接,则将收到的params存储到会话变量中,并将用户重定向到注册表单并使用内置的Devise函数after_sign_in_path_for来如果Rails检测到会话变量,则将其重定向到您的表单。

看起来应该是这样的:

# forms_controller.rb
class FormsController < ApplicationController

# Make sure not to filter 'create' as we'll be handling that with our redirect
before_filter :authenticate_user!, :except => [:create]

...

def create
  # Check to see if the user is registered/logged in
  if current_user.nil?
     # Store the form data in the session so we can retrieve it after login
     session[:form_data] = params
     # Redirect the user to register/login
     redirect_to new_user_registration_path    

  else
    # If the user is already logged in, proceed as normal
    ...

  end
end


# application_controller.rb
def after_sign_in_path_for(resource)

  # redirect to the form if there is a form_data in the session
  if session[:form_data].present?

    #redirect to your form path

  else
    #if there is not temp list in the session proceed as normal
    super
  end

end

要重新填充表单,请在您的控制器操作&#39; new&#39;中执行以下操作:

if session[:form_data]
  @my_form = Form.new(session[:form_data])
  session[:form_data] = nil
  @my_form.valid? # run validations to populate the errors[]
else
  @my_form = Form.new
end

有关它的更多信息,请查看this tutorial