4

我在 rails 4.1 应用程序中使用巫术进行用户身份验证。一切正常。但是当我尝试更新用户模型的特定属性(通过巫术验证)时,我收到一个错误,即密码为空且太短。

这是控制台的一个片段

> user = User.last  
=> # I get the user  
> user.update(about_me: "I'm a user")  
=> false  
> user.update(about_me: "I'm a user", password: "secret")  
=> true

这是我的模型代码
app/models/user.rb

class User < ActiveRecord::Base  
  authenticates_with_sorcery!  
  validates :password, presence: true, length: { minimum: 6 }  
  .....
end  

我的控制器代码
app/controllers/users_controller.rb

class UsersController < ApplicationController
  .....
  def edit
    @user = User.find(params[:id])
  end

  def update
    @user = User.find(params[:id])
    if @user.update(user_params)
        redirect_to @user
        flash[:notice] = "Profile successfully updated"
    else
        render 'edit'
    end
  end

  private
      def user_params
        params.require(:user).permit(:username, :name, :email, :password, :about_me)
      end

end

还有我的更新表单
app/views/users/edit.html.erb

<%= form_for @user, method: :put do |f| %>
  <% if @user.errors.any? %>
    <div class="alert">
      <p><%= pluralize(@user.errors.count, 'error') %></p>
      <ul>
        <% @user.errors.full_messages.each do |msg| %>
          <li><%= msg %></li>
        <% end %>
      </ul>
    </div>
  <% end %>
  <%= f.text_field :username, placeholder: 'Username' %>
  <%= f.text_field :name, placeholder: 'Name' %>
  <%= f.email_field :email, placeholder: 'Email' %>
  <%= f.text_area :about_me, placeholder: 'About me' %>
  <%= f.password_field :password, placeholder: 'Password' %>
  <%= f.submit 'Save Changes', class: 'button' %>
<% end %>

如果我从表单中删除密码字段,我会收到有关密码为空及其长度的错误。这是与巫术有关还是我与rails本身缺少的东西?有没有更好的方法来更新让我们说只有电子邮件字段而不影响其他任何东西?

4

2 回答 2

5
class User < ActiveRecord::Base  
  authenticates_with_sorcery!  
  validates :password, presence: true, length: { minimum: 6 }, if: :new_user?

  private
  def new_user?
    new_record?
  end
end  

只有当它是一个 new_record 时才会检查验证,我们为此添加了我们自己的私有验证方法 new_user?。此函数将在您的正常注册/注册期间返回 true。因此,在这些注册中,只需要密码验证。

在编辑期间,用户当然会是现有用户/新记录?将返回假。因此,将跳过密码验证。

第二种方式:

class User < ActiveRecord::Base 
  attr_accessor :skip_password
  validates :password, presence: true, length: { minimum: 6 }, unless: :skip_password
end

 #users_controller.rb 
def update
  @user = User.find(params[:id])
  @user.skip_password = true 
  if @user.update(user_params)
     redirect_to @user
  else
     render 'edit'
  end
end

在这里,我们添加了我们自己的自定义 attr_accessor skip_password。如果 skip_password 值设置为 true,则在编辑/更新期间将跳过密码验证。

我希望这两种方法都能帮助你:)

于 2015-01-31T14:07:19.587 回答
3

如果将来有人寻找这个主题,可以使用changesActiveRecord 模型的映射:

class User < ActiveRecord::Base  
  authenticates_with_sorcery!  
  validates :password, presence: true, length: { minimum: 6 }, if: -> {new_record? || changes[:crypted_password]}
  .....
end

:crypted_password的值在哪里sorcery_config.crypted_password_attribute_name

目前,简单密码身份验证巫术维基文章中也指出了这种验证条件。

于 2018-06-20T14:09:37.747 回答