2017-10-12 108 views
0

我有一個簡單的應用程序使用Devise。 如何在註冊時自動創建用戶並將其分配給新客戶端?註冊後自動創建用戶

我有一個客戶表和會員表,他們都需要一個用戶,所以我創建了一個用戶表,客戶和分支機構屬於用戶。

這個想法是,在用戶註冊後,它會根據給定的電子郵件和客戶端在其電子郵件中收到的自動生成的密碼創建客戶端和用戶。當他們登錄時,系統會提示他們更改密碼。

我有一個客戶註冊頁面,他們把他們的信息,然後點擊sign_up。我想要的是自動爲該客戶端生成一個用戶,以便他們可以在下次訪問時登錄。

這是我試過到目前爲止:

clients_controller.rb

def create 
    @client = Client.new(client_params) 
    @user = User.new(user_params[password: random_password, password_confirmation: random_password]) 

    respond_to do |format| 
     if @client.save && @user.save 
     format.html { redirect_to @client, notice: 'Client was successfully created.' } 
     format.json { render :show, status: :created, location: @client } 
     else 
     format.html { render :new } 
     format.json { render json: @client.errors, status: :unprocessable_entity } 
     end 
    end 
    end 


    private 

    def set_client 
     @client = Client.find(params[:id]) 
    end 

    def client_params 
     params.require(:client).permit(:first_name, :last_name, :cellphone, :email, :affiliate_id, :user_id) 
    end 

    def user_params 
    params.require(:client).permit(:email) 
    end 

    def random_password 
    [*('a'..'z'),*('0'..'9')].shuffle[0,8].join 
    end 

回答

1

試圖改變 @user = User.new(user_params[password: random_password, password_confirmation: random_password])

user_parameter = user_params.merge(password: random_password, password_confirmation: random_password) 

@user = User.create!(user_parameter) 
+0

謝謝,夥計。我認爲隨機密碼每次被調用時都會生成,所以它不匹配。所以,我創建了一個變量來存儲它,然後叫變量,而不是: 高清user_parameter RANDOM_NUMBER = random_password user_params.merge(密碼:RANDOM_NUMBER,password_confirmation:RANDOM_NUMBER) 結束 – Allan

+0

的我怎麼能收集用戶ID和保存任何想法它在客戶端下的user_id? – Allan

+0

我使用@ client.update_columns(user_id:@ user.id)並在保存時調用它。 – Allan