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

时间:2017-05-26 16:57:12

标签: ruby-on-rails ruby-on-rails-5

所以,我一直在开发一个应用程序(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

当我尝试访问localhos:3000时出现以下错误:

  

未定义的方法`server_exists?&#39; for Player(call&#39; Player.connection&#39;   建立连接):类

有人知道如何解决它吗?

谢谢!

2 个答案:

答案 0 :(得分:2)

  

您可以将:if:unless选项与符号相关联   对应于将被调用的方法的名称   在验证发生之前。

尝试使用:server_exists?代替server_exists?

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

答案 1 :(得分:0)

您需要为方法名称使用符号:

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

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