我有以下代码,它正在对所有片段内容进行验证,以检查字数是否与常量相符,但我不断收到以下错误:
undefined method `[]' for nil:NilClass
Extracted source (around line #36):
current_snippets_size = (self.book.get_word_count || 0) + word_count
errors.add(:base, "Content size is too big") unless word_count < BOOK_SIZE[book_limit]['per'] && current_snippets_size < BOOK_SIZE[book_limit]['total']
end
这是模型的完整代码 (snippet.rb)
BOOK_SIZE = {
0 => {"per" => 5, "total" => 50},
1 => {"per" => 6 , "total" => 60},
2 => {"per" => 7, "total" => 70}
}
def size_limit
book_limit = self.book.size
word_count = self.content.scan(/\w+/).size
current_snippets_size = (self.book.get_word_count || 0) + word_count
binding.pry
errors.add(:base, "Content size is too big") unless word_count < BOOK_SIZE[book_limit]['per'] && current_snippets_size < BOOK_SIZE[book_limit]['total']
end
因为snippets 是books 的子节点,所以这里是word_count
book.rb 中列出的:
def get_word_count
@word_count = []
self.snippets.each do |c|
@word_count << c.content.scan(/\w+/).size
end
@word_count = @word_count.inject(:+)
end
编辑:撬调试
31: def size_limit
=> 32: binding.pry
33: book_limit = self.book.size
34:
35: word_count = self.content.scan(/\w+/).size
36:
37: current_snippets_size = (self.book.get_word_count || 0) + word_count
38:
39: errors.add(:base, "Content size is too big") unless word_count < BOOK_SIZE[book_limit]['per'] && current_snippets_size < BOOK_SIZE[book_limit]['total']
40: end
[1] pry(#<Snippet>)> p book_limit
nil
=> nil
[2] pry(#<Snippet>)> p word_count
nil
=> nil
[3] pry(#<Snippet>)> errors.any?
=> false
[4] pry(#<Snippet>)> errors.blank?
=> true
我尝试使用 PRY,但我还是调试方面的新手,一些描述通过 PRY 调试的最佳方法的文档将非常有用。
谢谢。