【问题标题】:update_attributes NoMethodError when form value contains question mark in rails 3.1当表单值在rails 3.1中包含问号时,update_attributes NoMethodError
【发布时间】:2024-01-18 10:35:02
【问题描述】:

当我尝试使用包含“?”的值更新字段时,update_attributes 返回:

**NoMethodError**
You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.reverse

我的控制器能够:

  • 使用“?”创建记录作为字段名称。
  • 如果字段包含“?”,则编辑/保存记录保持不变
  • 如果字段包含“?”,则编辑/保存记录改为“测试”

不能:

  • 如果字段包含“?”,则编辑/保存记录改为'?test'或'test?'
  • 如果包含“测试”的字段更改为“?”,则编辑/保存记录

我想 active_record 会忽略未更改的字段,这就是代码在这种情况下有效的原因。

我还在日志中看到 BEGIN 和 ROLLBACK,所以我认为错误是由于 update_record 在将字符串传递到数据库之前未能引用字符串引起的。这是一个错误还是我应该明确引用表单输入?

我的更新方法:

def update
  @interface = Interface.find(params[:id])
  if @interface.update_attributes(params[:interface])
     redirect_to :action => 'show', :id => @interface.id
  else
     redirect_to :action => 'edit' 
  end
end

模型是空白的。

使用 update_attributes!,消息是(编辑,静止):

NoMethodError in Admin::InterfacesController#update
You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.reverse

抱歉,我提到的 ArgumentError 无关紧要。

原始堆栈跟踪:http://pastebin.com/JQ3Cmrba


通过恢复到 rails 3.0.7 和 mysql 0.2.7 修复。

可能的原因:

“用户名”和“密码”是接口表中的字段。 interface_controller 继承自 base_controller:

class Admin::BaseController < ApplicationController

  layout 'admin'
  before_filter :authenticate

  def index
  end
  protected

  def authenticate
     authenticate_or_request_with_http_basic do |username, password|
        if username == 'test' and password == 'pass'
           true
        else
           false
        end
     end
  end
end

【问题讨论】:

  • 一些与错误/堆栈跟踪相关的代码会有所帮助
  • 尝试使用update_attributes! 运行它。这将引发异常(如果引发)并可能提供更多有用的信息。
  • 你能在最新的 Ruby 1.9.2 补丁集中试试这个吗?
  • 如果必须,我可以。 3.1 gems 与 ruby​​ 1.8.7 不兼容吗?
  • @Zameer。使用 1.9.2 并没有立即修复错误。目前我已经通过将 rails 降级到 3.0.7 并将 mysql2 降级到 0.2.7 来解决它。

标签: ruby-on-rails activerecord update-attributes


【解决方案1】:

我有同样的错误。对我来说,这是我使用 git 版本修复的 gem 'activerecord-jdbc-adapter':

-gem 'activerecord-jdbc-适配器'
+gem 'activerecord-jdbc-adapter', :git => 'https://github.com/jruby/activerecord-jdbc-adapter.git'

似乎这已在此提交中修复:https://github.com/jruby/activerecord-jdbc-adapter/commit/837cd489591afbb24f6ba4d36a15a6c4da82b063

【讨论】:

    【解决方案2】:

    似乎错误出现在一些 ActiveRecord 回调中。尝试在一些 after_save 或其他回调中查找它。在某个地方,您在 nil 对象上使用了 reverse 函数。当值包含 ? 时,处理结果可能是您得到 nil。如果您发布回调代码,我们可以提供更好的帮助。

    【讨论】:

    • 我认为这可能不是原因,但我会用 base_controller 的内容更新我的帖子。正如我在注意到您的回复之前对 Zameer 所说的那样,我通过恢复到 rails 3.0.7 和 mysql2 0.2.7 来修复错误。