【问题标题】:ruby/rails NoMethodError? when using custom validation method红宝石/导轨NoMethodError?使用自定义验证方法时
【发布时间】:2010-01-17 06:58:22
【问题描述】:

我是 ruby​​ 和 rails 的新手,遇到了一个相当奇怪的错误:

class Person < ActiveRecord::Base
    validates_presence_of :description, :if => require_description_presence?

    def require_description_presence?
        self.can_send_email
    end
end

提高

NoMethodError in PeopleController#index

undefined method `require_description_presence?' for #<Class:0x4c4fadc> 

【问题讨论】:

    标签: ruby-on-rails ruby validation activerecord


    【解决方案1】:

    您应该将验证方法作为符号传递:

    validates_presence_of :description, :if => :require_description_presence?
    

    【讨论】:

      【解决方案2】:

      你可以让它更短更甜。 :if 子句将同样容易地获取一个属性。因此,如果 can_send_email 是 Person 的布尔属性,这将起作用:

      class Person < ActiveRecord::Base
        validates_presence_of :description, :if => :can_send_email?
      end
      

      不需要创建另一个方法来检查这个属性。如果您注意到can_send_email 末尾的额外问号,那是因为 Rails 允许您使用布尔属性来做到这一点。我喜欢它,因为它使代码的目的更加清晰。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多