0

AR中有Person类和PersonName类,有has_many关系。现在我想验证 PersonName 模型的格式是字母还是空格。这是代码:

class Person < ActiveRecord::Base
  has_many :names, :class_name => "PersonName", :dependent => :destroy
  accepts_nested_attributes_for :names
end

class PersonName < ActiveRecord::Base
  belongs_to :person
  attr_accessible :full, :first, :middle, :last, :maiden, :title, :suffix, :nick
  validates_format_of :full, :first, :middle, :last, :maiden, :title, :suffix, :nick, :with => /^[a-zA-Z\s]*$/, :on => :save
end

似乎 validates_format 没有被执行。当我跑

PersonName.create(:full => '@#$@').valid?

在控制台中,它返回 true。我试图将其更改为 :on => :create 但它仍然返回 true。可能是什么问题呢?我需要在 Person 类中指定一些东西吗?

4

2 回答 2

0

I found the reason, should use create! instead of create.

于 2013-10-18T21:15:29.930 回答
0

来自 Rails 文档

Note: use \A and \Z to match the start and end of the string, ^ and $ match the start/end of a line

我认为这是你的问题

于 2013-10-18T18:00:29.810 回答