LoginSignup
0
0

More than 1 year has passed since last update.

[Rails] 謎のundefined methodの原因はvalidateの単複ミスだった

Posted at
class User < ApplicationRecord
  validates :validate_method

  def self.testmethod(url)
    User.find_by("url like ?", "%#{URI.parse(url).host}%").present?
  end

  private
    def validate_method
      
    end
end

定義したはずのtestmethodが呼び出せない。

irb(main):002:0> User.testmethod('http://test.com')
Traceback (most recent call last):
        2: from (irb):2
        1: from (irb):2:in `rescue in irb_binding'
NoMethodError (undefined method `testmethod' for User (call 'User.connection' to establish a connection):Class)

試しにメソッドを単純化してみたところ、エラーが変わり、原因が特定できた。

  def self.testmethod
    true
  end
irb(main):001:0> User.testmethod
Traceback (most recent call last):
        3: from (irb):1
        2: from app/models/user.rb:1:in `<top (required)>'
        1: from app/models/user.rb:4:in `<class:User>'
ArgumentError (You need to supply at least one validation)

一つだけバリデーションメソッドを入れているところが、validateではなくvalidatesになっていることによる不具合だった。
下記の修正でself.testmethod(url)も呼び出せた。

  validates :validate_method

  validate :validate_method

Railsは単数/複数の調整をいい感じにやってくれる分、設定ミスを起こすとエラーになりがちですね。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0