2016-09-25 66 views
0

我想序列號添加到創建的用戶像我一樣在這裏一個普通支架一代命名字段,「代碼」:在哪裏創建用戶(模型)的色器件控制器

def create 
    @tester = Tester.new(tester_params) 
    @tester.code = @tester.created_at.to_s + ":" + rand(1235).to_s + ":" +  rand(5123).to_s + ":" + rand(1523).to_s + ":" + SecureRandom.base64 
    respond_to do |format| 
     if @tester.save 
     format.html { redirect_to @tester, notice: 'Tester was successfully created.' } 
     format.json { render :show, status: :created, location: @tester } 
     else 
     format.html { render :new } 
     format.json { render json: @tester.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

我生成了一個設計用戶,並在設計控制器代碼中複製,以覆蓋設計會話處理程序。所以我覺得我overided用色器件本身的代碼的代碼,但我無法找到創建用戶在哪裏,我一直在尋找的色器件註冊碼:

def create 
build_resource(sign_up_params) 
resource.save 
yield resource if block_given? 
if resource.persisted? 
    if resource.active_for_authentication? 
    set_flash_message! :notice, :signed_up 
    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}" 
    expire_data_after_sign_in! 
    respond_with resource, location: after_inactive_sign_up_path_for(resource) 
    end 
else 
    clean_up_passwords resource 
    set_minimum_password_length 
    respond_with resource 
end 

我有added_code_to_users,現在我想做一個 current_user.code = secureRandom.base64什麼

+0

它的'build_resource' +'resource.save' –

+1

爲什麼在'before_create'回調'User'模型不能做到這一點? – Shobhit

+0

@Shobhit謝謝你的工作,如果你在這裏,你是一個拯救生命的人,我會親自接吻你的球。你真棒。 –

回答

2

resource(用戶)在build_resource(sign_up_params)被創建。

然而,Devise中的每個動作通常會產生資源。

yield resource if block_given? 

這使得它很容易通過調用super時傳遞塊簡單地擴展。

class TesterRegistrationContoller < Devise::RegistrationsController 
    # ... 
    def create 
    super do |resource| 
     # This runs before `.save` is called on the user. 
     begin 
     # do you really need all that other stuff? 
     code = SecureRandom.uuid 
     end while Tester.exists?(code: code) 
     resource.code = code 
    end 
    end 
end 
+0

我也要試試這個。我剛接觸rails,從來沒有聽說過這些東西。 –

0
class User < ActiveRecord::Base 
# Include default devise modules. Others available are: 
# :confirmable, :lockable, :timeoutable and :omniauthable 
devise :database_authenticatable, :registerable, 
    :recoverable, :rememberable, :trackable, :validatable 

before_create :set_code 
    def set_code 
     self.code = SecureRandom.base64 
    end 
end