2016-02-26 42 views
0

我試圖通過檢查用戶在註冊時輸入的代碼是否存在於表中來配置設備來驗證用戶註冊。爲了測試它,我目前只是針對靜態字符串測試輸入。有關如何去做的任何想法?問題在於,由於某種原因,字符串未從:ticket_id註冊字段傳遞到用戶類中的:invite_code_valid函數。當我查看變量中的內容時,它只是空白,並且在註冊時使用字符串「hello」給出我指定的錯誤消息。向ROR設計添加自定義字段驗證

代碼是英雄混帳,所以我不能鏈接到它,但我這樣做:

遷移:

class AddUserTicketIdField < ActiveRecord::Migration 
    def change 
    change_table :users do |t| 
     t.text :ticket_id 
    end 
    end 
end 

在模型/ user.rb:

驗證:invite_code_valid,:on =>:創建

def invite_code_valid 
    unless self.ticket_id == "hello" 
     self.errors.add(:ticket_id, "membership code is not one we recognize, check again?") 
    end 
    end 

在色器件/註冊/ new.html.erb:

<div class="field"> 
    <%= f.label :Membership_code %><br /> 
    <%= f.text_field :ticket_id, autocomplete: "off" %> 
</div> 

要查看的代碼在所有工作我想驗證一個特定的電子郵件是這樣的:

def invite_code_valid 
    unless self.email == "[email protected]" 
     self.errors.add(:ticket_id, "membership code is not one we recognize, check again?") 
    end 
    end 

工程。當使用電子郵件[email protected]註冊時,註冊雖然,但不是。

這是怎麼回事,我錯過了關於設計是如何工作的?

------------已解決------------

Josh Deedens答案低於現場。謝謝!爲了將來的參考,這就是我所做的。

class ApplicationController < ActionController::Base 

    before_action :configure_permitted_parameters, if: :devise_controller? 

    protected 

    def configure_permitted_parameters 
     devise_parameter_sanitizer.for(:sign_up)  << :ticket_id 
    end 
end 

回答

2

我敢打賭,在你被咬傷strong_parameters:

從設計自述:https://github.com/plataformatec/devise#strong-parameters

當您自定義你自己的看法,你可能會增加新的屬性形成。 Rails 4將參數清理從模型轉移到控制器,導致Devise在控制器中處理這個問題。

該文檔去到舉這個例子

class ApplicationController < ActionController::Base 
    before_action :configure_permitted_parameters, if: :devise_controller? 

    protected 

    def configure_permitted_parameters 
    devise_parameter_sanitizer.permit(:sign_up, keys: [:username]) 
    end 
end 

所以嘗試添加configure_permitted_parameters方法您ApplicationController中,與相應的過濾器一起。並用:ticket_id替換:username密鑰,看看是否解決了您的ticket_id爲零的問題。

祝你好運!

+0

非常感謝!這幾乎解決了它!使用上面的蝙蝠代碼給出了一個方法錯誤出於某種原因,但我搜索了一下並修改了它。原問題的解決方案!太感謝了! – aerugo

+0

不客氣。很高興幫助! –