开发者

ruby/rails NoMethodError? when using custom validation method

i'v开发者_如何学运维 been new to ruby and rails and encountered a rather strange error:

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

    def require_description_presence?
        self.can_send_email
    end
end

raises

NoMethodError in PeopleController#index

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


You should pass validation method as symbol:

validates_presence_of :description, :if => :require_description_presence?


You can make this even shorter and sweeter. The :if clause will take an attribute just as easily. So if can_send_email is a boolean attribute of Person, this will work:

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

No need to create another method just to check this attribute. And if you notice the extra question mark at the end of can_send_email, it's because Rails lets you do that with boolean attributes. I like it because it makes the code's purpose more clear.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜