2016-11-15 25 views
0

我正在使用Rails 4和Devise gem,我的用戶模型被稱爲User(app/models/user.rb)。我想要的是有兩種不同類型的用戶,個人帳戶和企業帳戶存儲在我的用戶數據庫表中。Rails 4:使用Devise在單個用戶模型中驗證兩種類型的用戶

我的用戶模型是這樣的:

個人賬戶字段驗證

validates :first_name, :email, :gender, :date_of_birth, :last_name, presence: true, if: :personal_account?  

企業賬戶字段驗證

validates :company, :zip, :representante, :founders, :founded_date, :address, :city, :country, :state, :sector, presence: true, if: :business_account? 
validates_length_of :zip, minimum: 5, too_short: 'please enter at least 5 characters', if: :business_account? 

在視圖/設計/註冊/新我有兩個radio_button到在我的用戶模型中使用的個人帳戶和商業帳戶之間進行選擇以過濾和驗證字段。

def personal_account? 
self.account_type == "Personal Account" 
end 

def business_account? 
self.account_type == "Business Account" 
end 

我在Devise驗證的兩個帳戶之間也有共同的字段。常見字段爲:

email 
password 
password_confirmation 

我可以創建一個沒有問題的個人帳戶。但是,當我選擇商業帳戶的radio_button時,請填寫所有字段,並嘗試提交表單,它將無法爲電子郵件和密碼字段提供「不可空白」驗證錯誤。

的意見/設計/註冊/ new.html.erb看起來是這樣的:

<%= simple_form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %> 
    <%= f.error_notification %> 

    <div class="form-inputs"> 

     <%= f.radio_button :account_type, 'Personal Account', checked: 'checked', wrapper_html: { class: 'radioName'}, data: {behavior: "clickable"} %><span class="ratiospace"></span><span>Personal Account<span class="space"></span></span> 

     <%= f.radio_button :account_type, 'Business Account', wrapper_html: { class: 'radioName'}, data: {behavior: "clickable"} %><span class="ratiospace"></span><span>Business Account</span> 

    #more code below 

我不希望有個人和企業賬戶兩種不同的模式,因爲我用的是電子商務的寶石誰要求只有一個模型代表我的應用程序中的用戶。我也認爲我不需要創建一個角色模型,因爲它已經在電子商務中作爲cancan能力實施。

任何幫助將不勝感激。非常感謝你提前。

回答

0

我會受到誘惑去嘗試自定義驗證如下所示:

http://guides.rubyonrails.org/active_record_validations.html

class UserValidator < ActiveModel::Validator 
    def validate(record) 
    if record.business_account? 
     if (there's a field missing)... 
     record.errors[:base] << "Invalid business account" 
     end 
    elsif (record.personal_account?) 
     ... some other validation 
    end 
    end 
end 

class User < ApplicationRecord 
    validates_with GoodnessValidator 
end 
+0

的答案帕特里斯謝謝,但我嘗試和沒有工作。除常用字段,電子郵件,passowrd和password_confirmation外,所有業務帳戶字段均經過驗證。這些常用字段在我創建個人帳戶時進行驗證,但在切換到企業帳戶並嘗試創建帳戶時未驗證。真的不知道發生了什麼事?我想也許可能是我打電話來隱藏或顯示字段的jQuery。 – aminhs

相關問題