2017-05-26 59 views
0

所以,我一直工作在一個應用程序(Rails的5),我想確認是否由用戶選擇的屬性(服務器)是我想要的範圍。Rails的條件驗證拋出未定義的方法型號

class Player < ApplicationRecord 
    validates :nick, presence: true, length: { maximum: 20 } 
    validates :description, length: { maximum: 275 } 
    validates :server, presence: true, if: server_exists? 

    def server_exists? 
    server == "NA" 
    end 

end 

當我試圖訪問localhos:3000我得到以下錯誤:

undefined method `server_exists?' for Player (call 'Player.connection' to establish a connection):Class

有誰知道如何解決它?

謝謝!

回答

2

You can associate the :if and :unless options with a symbol corresponding to the name of a method that will get called right before validation happens.

:server_exists?嘗試,而不是server_exists?

validates :server, presence: true, if: :server_exists? 
+0

考慮在*爲什麼*出現這種情況的闡述特別是它自身的錯誤。 (被直接稱爲ClassModel,這裏不存在) –

+0

謝謝!我會研究爲什麼當不使用「:」時會發生這種錯誤。 – Matheus

+0

不客氣!我想你可以看看到['::加載ActiveModel驗證#validates'(https://github.com/rails/rails/blob/cdb9d7f481a6b299cd53a0f647397da60d806a21/activemodel/lib/active_model/validations /validates.rb#L104)以更好地瞭解它是如何工作的。 –

相關問題