为啥 update_attributes 会破坏我的 Rails 应用程序?

Posted

技术标签:

【中文标题】为啥 update_attributes 会破坏我的 Rails 应用程序?【英文标题】:Why does update_attributes break my Rails app?为什么 update_attributes 会破坏我的 Rails 应用程序? 【发布时间】:2011-05-06 23:16:37 【问题描述】:

原始问题

我在 Ruby 1.9.2 上运行 Rails 3.0.1。以下是相关的模型、控制器和视图。

代码

user.rb:

class User < ActiveRecord::Base
  belongs_to :directory

  attr_accessor :new_password, :new_password_confirmation

  validates_confirmation_of :new_password, :if => :password_changed?

  before_save :hash_password, :if => :password_changed?

  def self.authenticate(login, password)

    # Check to see if the user exists
    if user = find_by_login(login)

      # If this is an directory user, authenticate them against their directory
      if user.directory
        return directory_auth user, password

      # Otherwise, authenticate them against the local database
      elsif user.hash == Digest::SHA2.hexdigest(user.salt + password)
        return user
      end
    end
    return nil
  end

  def password_changed?
    !@new_password.blank?
  end

  private

  def hash_password
    self.salt = ActiveSupport::SecureRandom.base64 8
    self.hash = Digest::SHA2.hexdigest(self.salt + @new_password)
  end

  def self.directory_auth(user, password)

    directory = user.directory
    directory.bind['%s'] = user.login

    ldap = Net::LDAP.new
    if directory.use_simple_tls?
      ldap.encryption :simple_tls
    end
    ldap.host = directory.host
    ldap.port = directory.port
    ldap.auth directory.bind, password

    return user if ldap.bind
    return nil
  end
end

users_controller.rb:

class UsersController < ApplicationController

  def index
    @users = User.all
  end

  def show
    @user = User.find params[:id]
  end

  def new
    @user = User.new
  end

  def create
    @user = User.new params[:user]

    if @user.save
      flash[:notice] = "#@user.login was created"
      redirect_to @user
    else
      flash[:notice] = 'The user could not be created' 
      render :action => 'new'
    end
  end

  def edit
    @user = User.find params[:id]
  end

  def update
    @user = User.find params[:id]

    @user.attributes = params[:user] # this works
    # @user.update_attributes params[:user] # this does NOT work

    if @user.save # I realize this is redundant if update_attributes is working
      flash[:notice] = "#@user.login was updated" 
      redirect_to @user
    else
      flash[:notice] = 'The user could not be updated' 
      render :action => 'edit'
    end
  end

  def destroy
    @user = User.find params[:id]
    @user.destroy

    flash[:notice] = "#@user.login was deleted"
    redirect_to users_url
  end
end

users.html.erb:

<%= form_for @user do |f| %>
  <%= f.label :login %>:
  <%= f.text_field :login %>
  <br>
  <%= f.label :new_password %>:
  <%= f.password_field :new_password %>
  <br>
  <%= f.label :new_password_confirmation %>:
  <%= f.password_field :new_password_confirmation %>
  <br>
  <% if directories = Directory.all.empty? %>
    No directories defined. You can <%= link_to 'add a directory', new_directory_path %>.
  <% else %>
    <%= f.label :directory_id %>:
    <%= f.collection_select :directory_id, Directory.all, :id, :name,  :include_blank => 'None'  %>
  <% end %>
  <br>
  <%= f.label :admin, 'Administrator?' %>:
  <%= f.check_box :admin %>
  <br>
  <%= f.submit %>
<% end %>

schema.rb:

ActiveRecord::Schema.define(:version => 20101107005603) do

  create_table "directories", :force => true do |t|
    t.string   "host"
    t.string   "bind"
    t.boolean  "use_simple_tls"
    t.integer  "port"
    t.string   "name"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "users", :force => true do |t|
    t.string   "login"
    t.string   "hash"
    t.string   "salt"
    t.boolean  "admin"
    t.integer  "directory_id"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

end

我有另一个非常相似的目录的模型/控制器/视图,但没有虚拟访问器或其他模型 ID,update_attributes 在其中可以正常工作。我使用rails g scaffold users name:string password:string 做了一个快速测试应用程序,所有 CRUD 操作都可以正常工作。

这让我发疯了!我找到了一种解决方法,但我真的很想了解为什么update_attributes 在这里不起作用。当我运行更新操作时,我得到了这个:

UsersController#update 中的类型错误

无法将 nil 转换为整数

Rails.root: /home/force/proj

app/controllers/users_controller.rb:34:in `update'

全栈跟踪

activerecord (3.0.1) lib/active_record/connection_adapters/abstract/database_statements.rb:318:in `uniq' activerecord (3.0.1) lib/active_record/connection_adapters/abstract/database_statements.rb:318:in `commit_transaction_records' activerecord (3.0.1) lib/active_record/connection_adapters/abstract/database_statements.rb:165:in `transaction' activerecord (3.0.1) lib/active_record/transactions.rb:204:in `transaction' activerecord (3.0.1) lib/active_record/transactions.rb:287:in `with_transaction_returning_status' activerecord (3.0.1) lib/active_record/persistence.rb:126:in `update_attributes' app/controllers/users_controller.rb:34:in `update' actionpack (3.0.1) lib/action_controller/metal/implicit_render.rb:4:in `send_action' actionpack (3.0.1) lib/abstract_controller/base.rb:150:in `process_action' actionpack (3.0.1) lib/action_controller/metal/rendering.rb:11:in `process_action' actionpack (3.0.1) lib/abstract_controller/callbacks.rb:18:in `block in process_action' activesupport (3.0.1) lib/active_support/callbacks.rb:435:in `_run__805567340__process_action__482539529__callbacks' activesupport (3.0.1) lib/active_support/callbacks.rb:409:in `_run_process_action_callbacks' activesupport (3.0.1) lib/active_support/callbacks.rb:93:in `run_callbacks' actionpack (3.0.1) lib/abstract_controller/callbacks.rb:17:in `process_action' actionpack (3.0.1) lib/action_controller/metal/instrumentation.rb:30:in `block in process_action' activesupport (3.0.1) lib/active_support/notifications.rb:52:in `block in instrument' activesupport (3.0.1) lib/active_support/notifications/instrument.rb:21:in `instrument' activesupport (3.0.1) lib/active_support/notifications.rb:52:in `instrument' actionpack (3.0.1) lib/action_controller/metal/instrumentation.rb:29:in `process_action' actionpack (3.0.1) lib/action_controller/metal/rescue.rb:17:in `process_action' actionpack (3.0.1) lib/abstract_controller/base.rb:119:in `process' actionpack (3.0.1) lib/abstract_controller/rendering.rb:40:in `process' actionpack (3.0.1) lib/action_controller/metal.rb:133:in `dispatch' actionpack (3.0.1) lib/action_controller/metal/rack_delegation.rb:14:in `dispatch' actionpack (3.0.1) lib/action_controller/metal.rb:173:in `block in action' actionpack (3.0.1) lib/action_dispatch/routing/route_set.rb:62:in `call' actionpack (3.0.1) lib/action_dispatch/routing/route_set.rb:62:in `dispatch' actionpack (3.0.1) lib/action_dispatch/routing/route_set.rb:27:in `call' 机架安装 (0.6.13) lib/rack/mount/route_set.rb:148:in `block in call' 机架安装 (0.6.13) lib/rack/mount/code_generation.rb:93:in `block in identify' 机架安装 (0.6.13) lib/rack/mount/code_generation.rb:103:in `optimized_each' 机架安装 (0.6.13) lib/rack/mount/code_generation.rb:92:in `recognize' 机架安装 (0.6.13) lib/rack/mount/route_set.rb:139:in `call' actionpack (3.0.1) lib/action_dispatch/routing/route_set.rb:492:in `call' actionpack (3.0.1) lib/action_dispatch/middleware/best_standards_support.rb:17:in `call' actionpack (3.0.1) lib/action_dispatch/middleware/head.rb:14:in `call' rack (1.2.1) lib/rack/methodoverride.rb:24:in `call' actionpack (3.0.1) lib/action_dispatch/middleware/params_parser.rb:21:in `call' actionpack (3.0.1) lib/action_dispatch/middleware/flash.rb:182:in `call' actionpack (3.0.1) lib/action_dispatch/middleware/session/abstract_store.rb:149:in `call' actionpack (3.0.1) lib/action_dispatch/middleware/cookies.rb:287:in `call' activerecord (3.0.1) lib/active_record/query_cache.rb:32:in `block in call' activerecord (3.0.1) lib/active_record/connection_adapters/abstract/query_cache.rb:28:in `cache' activerecord (3.0.1) lib/active_record/query_cache.rb:12:in `cache' activerecord (3.0.1) lib/active_record/query_cache.rb:31:in `call' activerecord (3.0.1) lib/active_record/connection_adapters/abstract/connection_pool.rb:355:in `call' actionpack (3.0.1) lib/action_dispatch/middleware/callbacks.rb:46:in `block in call' activesupport (3.0.1) lib/active_support/callbacks.rb:415:in `_run_call_callbacks' actionpack (3.0.1) lib/action_dispatch/middleware/callbacks.rb:44:in `call' rack (1.2.1) lib/rack/sendfile.rb:107:in `call' actionpack (3.0.1) lib/action_dispatch/middleware/remote_ip.rb:48:in `call' actionpack (3.0.1) lib/action_dispatch/middleware/show_exceptions.rb:46:in `call' railties (3.0.1) lib/rails/rack/logger.rb:13:in `call' rack (1.2.1) lib/rack/runtime.rb:17:in `call' activesupport (3.0.1) lib/active_support/cache/strategy/local_cache.rb:72:in `call' rack (1.2.1) lib/rack/lock.rb:11:in `block in call' :10:在“同步”中 rack (1.2.1) lib/rack/lock.rb:11:in `call' actionpack (3.0.1) lib/action_dispatch/middleware/static.rb:30:in `call' railties (3.0.1) lib/rails/application.rb:168:in `call' railties (3.0.1) lib/rails/application.rb:77:in `method_missing' railties (3.0.1) lib/rails/rack/log_tailer.rb:14:in `call' rack (1.2.1) lib/rack/content_length.rb:13:in `call' 机架 (1.2.1) lib/rack/handler/webrick.rb:52:in `service' /home/force/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/webrick/httpserver.rb:111:在“服务”中 /home/force/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/webrick/httpserver.rb:70:in `run' /home/force/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/webrick/server.rb:183:in `block in start_thread'

请求参数

"utf8"=>"✓", "_method"=>"放", "authenticity_token"=>"OvMUeM9hqfPASC0NS+Th07GELu6B+dQCCTtm3gWdJE4=", "用户"=>"登录"=>"本地", "new_password"=>"[过滤]", "new_password_confirmation"=>"[过滤]", "directory_id"=>"", “管理员”=>“0”, "commit"=>"更新用户", “id”=>“13”

完整的源代码

如果您想尝试一下,可以在http://github.com/sidewaysmilk/deezy 下载完整源代码并编辑app/controllers/users_controller.rb 以在update 操作中使用@user.update_attributes params[:user]

【问题讨论】:

您的用户模型的架构是什么样的? 您可以添加您的参数在提交表单时的样子吗? (来自服务器日志) 我用参数、堆栈跟踪和完整源代码的链接修改了我的问题。 如果该字段不为空,您有一个 before_save 回调用户更新密码。这就是我开始寻找的地方 谢谢,道格。我会试着戳那个。我只是觉得令人困惑的是,我在堆栈跟踪中看不到类似的东西。 【参考方案1】:

好的。我真的觉得自己很傻。我很惊讶没有人发现这个。

在我的模型中,我命名了我的一个属性。 hash,所以要访问它,我会说@user.hash

ActiveRecord::Base#hash 是 already defined!

所以我搞砸了。当 ActiveRecord 试图执行事务时,它试图设置一个类似

的值
@user.hash = password_hash

ActiveRecord::Base#hash= 需要一个整数,如果密码被更改,password_hash 输出一个字符串,否则为 nil。

所以永远不要命名列哈希!在选择列名时请查看文档以避免冲突。

【讨论】:

拯救了我的一天! hash 现在在我的任何类型变量或字段的心理黑名单上:)【参考方案2】:

看起来问题可能是用户 ID 是主键,并且正在尝试更新。如果您使用 'bangversion ofupdate_attributes:update_attributes!` 会收到什么错误消息?

【讨论】:

如果我使用update_attributes!,我会得到完全相同的行为。我会看看我能找到关于 @user.id 更新的信息。那是一个很好的收获。我不知道为什么我的表单将@user.id 作为参数提交。有什么想法吗? 看起来提交 id 是正常行为。我在使用脚手架的全新 Rails 应用程序中看到了相同的行为。【参考方案3】:

如果没有完整的堆栈跟踪,很难说,但错误消息“无法将 nil 转换为整数”是您要追踪的关键。同样,我们希望查看失败请求的日志。我认为参数:日志的行可能会阐明这个问题。

以下更新:

你能成功地将相同的参数传递给 rails 控制台中的@user.update_attributes 吗?

rails console

user = User.find(42) # whatever a good test user's id is
user_params = "login"=>"local", "new_password"=>"supersecret", "new_password_confirmation"=>"supersecret", "directory_id"=>"",  "admin"=>"0"
user.update_attributes!(user_params)

这有什么不同吗?

【讨论】:

当然。对不起。当我发布这个问题时,我已经筋疲力尽了。我应该包括堆栈跟踪。我马上更新。 我最初应该提到,使用堆栈跟踪我能够将我的问题跟踪到 update_attributes,但除此之外我无能为力。我不知道所谓的nil 是什么。我认为这可能与我的attr_accessors 有关,因为如果我设置密码,它开始说它无法将 String(而不是 nil)转换为 Integer。 我从 github 克隆了您的源代码,并将用户控制器的更新操作更改为使用 update_attributes,它对我来说很好用。这是 Ruby 1.8.7 的版本。 我假设这是 Rails 3.0.1 在 Ruby 1.9.2 上的一个错误。我非常感谢您克隆我的资源并试一试。谢谢!我接受你的回答,并修改我的问题。

以上是关于为啥 update_attributes 会破坏我的 Rails 应用程序?的主要内容,如果未能解决你的问题,请参考以下文章

为啥添加 DataTables 会破坏我的页面? [关闭]

为啥多个 EXISTS 会破坏查询

为啥这个 Python 代码会破坏我的计算机? [关闭]

为啥 Rcpp 会破坏 xts 对象?

为啥 javafx 会破坏我的半透明游标?

为啥我的路由在调用破坏函数后会失败?