2017-05-26 78 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)以更好地了解它是如何工作的。 –

相关问题