我正在尝试编写一个自定义验证器来检查添加到我的“报告”中的“值”总和是否为每个类别(行为)的特定值(600)。我的代码如下:
报告:
class Report < ActiveRecord::Base
attr_accessible :value_ids, :values_attributes
accepts_nested_attributes_for :values
validate :validates_behaviour_sums
def values_by_behaviour
hash_hash = Hash.new( 0 )
values.each do |v|
au_hash = hash_hash[ v.behaviour ]
if au_hash.nil
au_hash = Hash.new( 0 )
end
au_hash.store( v.assessed_user, v )
hash_hash.store( v.behaviour, au_hash )
end
end
def validates_behaviour_sums
sums_valid = true
self.values_by_behaviour.each do |behaviour_values|
unless behaviour_values.values.sum == 600
sums_valid = false
end
end
unless sums_valid
errors.add(:values, "The behaviours in each category must equal 600." )
end
end
end
价值:
class Value < ActiveRecord::Base
attr_accessible :value, :assessed_user_id, :behaviour_id
belongs_to :assessed_user, :class_name => "User"
belongs_to :behaviour
belongs_to :report
validates :value, :assessed_user_id, :behaviour_id, :presence => true
end
当我尝试运行此代码时,出现以下错误:
ReportsController#create 中的 NoMethodError
0:Fixnum 的未定义方法“nil”
Rails.root: /Users/micah/dev/rails_projects/s2
应用程序跟踪
app/models/report.rb:23:in `block in values_by_behaviour'
app/models/report.rb:18:in `values_by_behaviour'
app/models/report.rb:45:in `validates_behaviour_sums'
app/controllers/reports_controller.rb:35:in `create'
似乎尚未设置集合“值”,但我不知道如何验证它们。它确实接受这些值并正确设置它们。