Rails 3.2 Uniqueness validation raises undefined method 'zero?' for nil:Nilclass

前端 未结 1 1850
感动是毒
感动是毒 2021-01-12 13:54

I am using Rails 3.2.0.

I have a simple model as show below

class Favorite < ActiveRecord::Base

  validates :lst, :presence => true
  validat         


        
相关标签:
1条回答
  • ActiveRecord AREL table aliasing is breaking

    The error is likely due to ActiveRecord AREL losing track of how to sum an empty array.

    The relevant line of code is in the file alias_tracker.rb:

     count.sum
    

    If count is an empty array then the line evaluates as:

     [].sum
    

    In Ruby that fails:

     $ irb
     > [].sum
     NoMethodError: undefined method `sum' for []:Array
    

    Rails ActiveSupport Enumerable#sum

    In Rails that succeeds because ActiveSupport is creating Enumerable#sum

     $ irb
     > require 'active_support/core_ext/enumerable'
     > [].sum  
     => 0
    

    Your problem is likely that some unrelated area of your app is also creating Enumerable#sum or Array#sum. The unrelated code is overwriting the Rails method.

    The could be happening in your code or in an unrelated gem. The Rails gem loads early, typically first in your Gemfile, and any later gem can interfere with Rails.

    How to fix it?

    Have you written a method named sum, perhaps within a module named Enumerable or Array? If so, that's a good place to start. You could rename your method, or you could try changing your method to match the Rails method by replacing your #sum code with this code:

    module Enumerable
      def sum(identity = 0, &block)
        if block_given?
          map(&block).sum(identity)
        else
          inject(:+) || identity
        end
      end
    end
    

    If you haven't written a method named sum in your code, then the conflict is likely in a gem you're using. Try commenting-out gems that you're using then reload your app.

    You can search for a gem that defines a method named sum like this:

    $ cd /usr/lib/ruby/gems 
    $ find | xargs grep "def sum\b"
    

    Are you using any gems named sixarm? If so, contact me and I'll fix them for you. These are by me, and a few of them do define #sum for use with statistics tools and utilties.

    Hope this helps. Can you post here if it solves your issue?

    0 讨论(0)
提交回复
热议问题