简体   繁体   English

为什么在Rails3.2.9中未调用validate函数?

[英]Why validate function is not called in Rails3.2.9?

The codes are as follows: 代码如下:

class Seat < ActiveRecord::Base
  attr_accessible :baggage, :flight_id, :name
  def validate(record)
    errors.add_to_base("You have too much baggage")
  end
end

I expected it throws error whenever a new record is wriiten into the database. 我希望每当有一条新记录写入数据库时​​,它都会引发错误。

However, nothing happened when new record wriiten into seats database by @seat.save 但是,当@seat.save新记录写入seats数据库时,什么也没有发生

Does anyone have ideas about this? 有人对此有想法吗?

validate(record) looks weird. validate(record)看起来很奇怪。 You should try 你应该试试

class Seat < ActiveRecord::Base
  attr_accessible :baggage, :flight_id, :name
  validate :valid_baggage

  def valid_baggage
    errors.add_to_base("You have too much baggage")
  end
end

Also note that you need to call @seat.save! 另请注意,您需要致电@seat.save! (instead of @seat.save ) in order to get the exception. (而不是@seat.save )以获取异常。 @seat.save will return true or false only ... but that's usually what you want, so consider if you really want to raise an exception. @seat.save仅返回true或false ...但这通常是您想要的,因此请考虑是否真的要引发异常。

仅当您实现自定义验证器时才需要record参数,否则该方法已经知道要验证的记录(自身)。

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

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