【问题标题】:Rails: Authlogic: Cannot update user attributes -- "Password field cannot be blank"Rails:Authlogic:无法更新用户属性——“密码字段不能为空”
【发布时间】:2011-01-23 23:17:44
【问题描述】:

我在用户页面上有一个简单的表单,允许用户在登录后更改他们自己的用户对象的某些属性。观点:

<% form_for @user, :url => {:controller => "teachers", :action => "update"} do |f| %>
    <%= f.error_messages %>
    <%= f.text_field :display_name %>
    <%= f.submit "Update" %>
<% end %>

我需要提供 URL,因为它不是标准的 RESTful 控制器。控制器提供

@user = current_user

到视图。

接下来,控制器中的update 操作尝试处理保存:

@user = current_user
if @user.update_attributes(params[:user])
  flash[:notice] = "Successfully updated profile."
  redirect_to root_url
else
  render :action => 'edit'
end

这应该会更新user 对象上的display_name 属性,将其保存到数据库中,然后重定向到root_url。相反,edit 操作会再次呈现,表单的 error_messages 指示“密码不能为空”。

这显然是 Authlogic 搞砸的事情!确认!这是我的整个Users.rb 文件:

class User < ActiveRecord::Base
  acts_as_authentic do |c|
    c.transition_from_crypto_providers = Authlogic::CryptoProviders::MD5
    c.crypto_provider = Authlogic::CryptoProviders::Sha512
    c.validate_email_field = false
    c.require_password_confirmation = false
    c.ignore_blank_passwords = true
    c.validate_password_field = false
  end

  belongs_to :school

  validates_presence_of :first_name, :last_name, :email, :password
  validates_uniqueness_of :email, :scope => :email, :case_sensitive => false, :message => "is already in our database. Please contact us for help reactivating your account."

  ROLES = %w[admin teacher student]

  def role_symbols
    [role.to_sym]
  end
end

如您所见,我已经关闭了我能找到的大多数 Authlogic 验证,以保持简单和实用!仍然没有运气。如果我将password_field 添加到编辑页面,那么它将成功运行——但当此表单仅用于更新他们的display_name 时,它也会更新用户的密码!

关于如何在不输入用户密码的情况下更新user 对象的属性的任何提示?

【问题讨论】:

  • 请向我们展示您当前的型号。
  • 感谢您的耐心等待,Trevoke。我只是设法弄清楚!将整个模型添加到我的问题中让我有机会返回并尝试其他潜在的陷阱……事实证明 Authlogic 根本不是问题。问题是我的validates_presence_of 每当我更新我的用户对象时就会触发。我在验证中添加了:on =&gt; :create 规定,现在一切正常。我仍然不明白为什么验证没有抱怨:first_name:last_name:email 没有被包括在内,但是嘿——它现在有效!再次感谢。

标签: ruby-on-rails authlogic


【解决方案1】:

原来问题不在于 Authlogic。问题是我的validates_presence_of 每当我更新我的用户对象时就会触发。我在验证中添加了:on =&gt; :create 规定,现在一切正常。

【讨论】:

  • 此解决方案的问题在于,如果您的用户有多个属性,并且您尝试更新其他属性之一,同时将密码字段留空,您实际上会将密码更改为“ ”。理想情况下,如果字段留空,您可以不更新密码。
【解决方案2】:

你试过了吗?

validate_password_field = false

【讨论】:

  • 试过了!没有运气。仍然收到Password can't be blank
猜你喜欢
  • 2011-10-28
  • 1970-01-01
  • 2010-11-30
  • 2015-03-15
  • 1970-01-01
  • 2021-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多