我有以下代码在所有代码段内容上运行验证,以检查字数与常量,但我不断收到以下错误:
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
因为代码段是图书的子代,所以这里是book.rb中列出的word_count
:
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调试的最佳方法的文档非常有用。
感谢。
答案 0 :(得分:1)
errors.add(:base, "book size is out of range") unless [0, 1, 2].include?(self.book.size)
答案 1 :(得分:1)
验证这些行是否始终返回值:
book_limit = self.book.size
word_count = self.content.scan(/ \ w + /)。size
如果是这样,他们可能会返回一个字符串对象,将其设为to_i
book_limit = self.book.size.to_i
word_count = self.content.scan(/\w+/).size.to_i