我有一个由设计生成的用户注册表单。提交表单并将用户对象保存到数据库时,我想创建并保存另一个对象,该对象在单独的控制器(leads_controller.rb)中生成并传递刚刚保存的用户对象。注册表单正在收集电子邮件,密码和密码确认。
保存用户后,我需要将该用户对象传递给leads_controller以调用new和create操作。
leads_controller.rb
class LeadsController < ApplicationController
include Databasedotcom::Rails::Controller
def new
@lead = Lead.new
end
def create
lead = Lead.new(params[:lead])
lead.Email = @user.email
end
end
的routes.rb
# User route
devise_for :users
devise_for :lenders, skip: :sessions, :controllers => {:registrations => "lenders/registrations"}
devise_for :businesses, skip: :sessions
root :to => 'business_account#dashboard', :constraints => lambda { |request| request.env['warden'].user.class.name == 'Business' }, :as => "business_root"
root :to => 'lender_account#dashboard', :constraints => lambda { |request| request.env['warden'].user.class.name == 'Lender' }, :as => "lender_root"
# Leads route
resources :leads
registrations_controller.rb
class Lenders::RegistrationsController < Devise::RegistrationsController
before_filter :update_sanitized_params
def new
super
end
def create
super
end
def update
super
end
private
def update_sanitized_params
devise_parameter_sanitizer.for(:sign_up) {|u| u.permit(:email, :password, :password_confirmation, :type)}
end
end
我可以在registrations_controller.rb中添加一个动作来将用户对象传递给leads_controller.rb吗?
答案 0 :(得分:1)
从
复制内容https://github.com/plataformatec/devise/blob/master/app/controllers/devise/registrations_controller.rb
并粘贴到 registrations_controller.rb
更改 routes.rb
# User route
devise_for :users, :controllers => { :registrations => "registrations" }
devise_for :businesses, skip: :sessions
root :to => 'business_account#dashboard', :constraints => lambda { |request| request.env['warden'].user.class.name == 'Business' }, :as => "business_root"
root :to => 'lender_account#dashboard', :constraints => lambda { |request| request.env['warden'].user.class.name == 'Lender' }, :as => "lender_root"
# Leads route
resources :leads
在 registration_controller.rb 中,将创建操作更改为
注意: - 另请参阅创建操作中的更改
def create
build_resource(sign_up_params)
resource_saved = resource.save
yield resource if block_given?
if resource_saved
if resource.active_for_authentication?
set_flash_message :notice, :signed_up if is_flashing_format?
sign_up(resource_name, resource)
respond_with resource, location: after_sign_up_path_for(resource)
else
set_flash_message :notice, :"signed_up_but_#{resource.inactive_message}" if is_flashing_format?
expire_data_after_sign_in!
respond_with resource, location: after_inactive_sign_up_path_for(resource)
end
else
clean_up_passwords resource
respond_with resource
end
end
在 registration_controller.rb
中def after_sign_up_path_for(resource)
redirect_to new_lead_path
#after_sign_in_path_for(resource)
end
Devise提供帮助方法
current_user
您可以在 leads_controller.rb 以及视图
中了解用户对象class LeadsController < ApplicationController
include Databasedotcom::Rails::Controller
def new
@lead = Lead.new
end
def create
lead = Lead.new(params[:lead])
lead.Email = current_user.email
end
end