0

我有这组课:

class Campaign < ActiveRecord::Base

  belongs_to :user
  validates_presence_of :title, :description

   def initialize
     validates_format_of_many([:title, :description])
   end

  def validates_format_of_many(inputs)
    if (!inputs.nil?)
      inputs.each do |input|
        validates_format_of input => /^[.]/, :allow_nil => false, :allow_blank => false
        puts YAML::dump('test1')
      end
    else
      puts YAML::dump('test2')
    end
  end
end

问题是我收到一些错误信息undefined method包括?对于 nil:NilClass` 并在堆栈中

/usr/lib/ruby/gems/1.8/gems/activerecord-2.3.14/lib/active_record/attribute_methods.rb:257:in `method_missing'
/var/www/gitorious/app/models/campaign.rb:13:in `validates_format_of_many'
/var/www/gitorious/app/models/campaign.rb:12:in `each'
/var/www/gitorious/app/models/campaign.rb:12:in `validates_format_of_many'
/var/www/gitorious/app/models/campaign.rb:7:in `initialize'
/var/www/gitorious/app/controllers/campaigns_controller.rb:28:in `new'
/var/www/gitorious/app/controllers/campaigns_controller.rb:28:in `new'
4

1 回答 1

2

首先如果你覆盖了initialize,你应该调用super,这将允许super_class执行它的初始化任务

def initialize
  validates_format_of_many([:title, :description])
  super
end

但建议 AR 使用回调。检查http://guides.rubyonrails.org/active_record_validations_callbacks.html

例子:

class Campaign < ActiveRecord::Base

  belongs_to :user
  validates_presence_of :title, :description

  after_initialize { validates_format_of_many([:title, :description]) }

  def validates_format_of_many(inputs)
    if (!inputs.nil?)
      inputs.each do |input|
        validates_format_of input => /^[.]/, :allow_nil => false, :allow_blank => false
        puts YAML::dump('test1')
      end
    else
      puts YAML::dump('test2')
    end
  end
end

Campaign.new但要小心,因为在创建新记录以及Campaign.find ...从数据库加载记录时会调用 validates_format_of_many

于 2013-03-17T13:34:03.177 回答