简体   繁体   English

Rails条件验证抛出未定义的模型方法

[英]Rails conditional validation throwing undefined method for Model

So, I've been working on an app (Rails 5) and I wanted to verify if the attribute (server) chosen by the user is in the scope I want. 因此,我一直在开发一个应用程序(Rails 5),我想验证用户选择的属性(服务器)是否在我想要的范围内。

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

When I try to access localhos:3000 I get the following error: 当我尝试访问localhos:3000时,出现以下错误:

undefined method `server_exists?' 未定义的方法“ server_exists?” for Player (call 'Player.connection' to establish a connection):Class 对于Player(调用“ Player.connection”以建立连接):Class

Does anybody know how to fix it? 有人知道如何解决吗?

Thanks! 谢谢!

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. 您可以将:if:unless选项与对应于方法名称的符号关联,该名称将在验证发生之前立即被调用。

Try with :server_exists? 尝试:server_exists? instead server_exists? 而是server_exists? :

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

You need to use a symbol for the method name: 您需要在方法名称中使用符号:

http://guides.rubyonrails.org/active_record_validations.html#using-a-symbol-with-if-and-unless http://guides.rubyonrails.org/active_record_validations.html#using-a-symbol-with-if-and-unless

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM