0

我有以下代码,它正在对所有片段内容进行验证,以检查字数是否与常量相符,但我不断收到以下错误:

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_countbook.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 调试的最佳方法的文档将非常有用。

谢谢。

4

2 回答 2

1
errors.add(:base, "book size is out of range") unless [0, 1, 2].include?(self.book.size) 
于 2013-10-27T23:00:32.307 回答
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

于 2013-10-28T09:23:15.923 回答