未定义的方法`+ @'为nil:移动到mysql后的NilClass rails

时间:2014-04-24 12:13:05

标签: mysql ruby-on-rails ruby ruby-on-rails-4

我将数据库移动到VM上的mysql。移动数据库后,当我尝试访问或保存数据到数据库时,我开始收到此错误,但某些模型更新工作正常。

我访问的模型有一些算术计算,我觉得是这个问题的原因。

错误是

undefined method `+@' for nil:NilClass

我也尝试从rails控制台使用此命令得到同样的错误

Settings.all

我想这是该方法方法的一部分

if params[:lat] and params[:lon] and params[:rad] and !params[:lat].empty? and
                    !params[:lon].empty? and !params[:rad].empty?

  lat = params[:lat].to_f
  lon = params[:lon].to_f
  rad = params[:rad].to_f
  ear = 6371.00

  min_lat = (lat) - (rad/ear)/180.0*Math::PI;
  max_lat = (lat) + (rad/ear)/180.0*Math::PI;

  min_lon = (lon) - (rad/ear/Math.cos(lon*Math::PI/180.0))/180.0*Math::PI;
  max_lon = (lon) + (rad/ear/Math.cos(lon*Math::PI/180.0))/180.0*Math::PI;

  @settings = @settings.includes(:settings_location)
    .where("settings_locations.latitude  > :min_lat AND " \
           "settings_locations.latitude  < :max_lat AND " \
           "settings_locations.longitude > :min_lon AND " \
           "settings_locations.longitude < :max_lon", {
               min_lat: min_lat,
               max_lat: max_lat,
               min_lon: min_lon,
               max_lon: max_lon});

堆栈跟踪

Started POST "/settings.json" for 127.0.0.1 at 2014-04-24 13:52:53 +0200

NoMethodError - undefined method `+@' for nil:NilClass:
  app/models/settings.rb:54:in `<top (required)>'
  activesupport (4.0.2) lib/active_support/dependencies.rb:424:in `block in load_file'
  activesupport (4.0.2) lib/active_support/dependencies.rb:616:in `new_constants_in'
  activesupport (4.0.2) lib/active_support/dependencies.rb:423:in `load_file'
  activesupport (4.0.2) lib/active_support/dependencies.rb:324:in `require_or_load'
  activesupport (4.0.2) lib/active_support/dependencies.rb:463:in `load_missing_constant'

setting.rb

class Settings < ActiveRecord::Base

has_one :settings_location

def to_builder
  Jbuilder.new do |json|
    json.location settings_location.to_builder
  end
end  //this line is 54 

1 个答案:

答案 0 :(得分:0)

根据评论,似乎只有少数情况可以在IRB中重现相同的错误消息。第一个是:

foo, bar = nil, nil
foo.send("+@", bar)            # undefined method `+@' for nil:NilClass

第二个是:

foo = nil
+foo                           # undefined method `+@' for nil:NilClass

eval上下文中,后者可能更像:

foo, bar = nil, nil
eval("foo = +#{bar.inspect}")  # undefined method `+@' for nil:NilClass

我个人的猜测是你的问题与后者有关。不是eval,而是其中过多的Ruby变体,例如define_method。实际调用很可能在Rail的内部某处并且与某些未初始化的变量相关 - 也许MySQL返回null,其中SQLite返回某些东西由于最近的模式更改而你没有想到?

就个人而言,我会尝试逐步缩小范围:

1。评论:

json.location settings_location.to_builder

如果错误消失,那么:

2.a)将其替换为:

builder = settings_location.to_builder
json.location builder

如果错误消息仍然相同,则:

2.b)尝试

Jbuilder.new

......没有障碍。

关键是,您希望将事情缩小到导致错误的特定方法,然后深入了解该方法的代码以查看什么是零而不应该是。 (也许该块缺少某种返回值?)