Rails Sorcery在没有密码的情况下更新模型的属性

时间:2015-01-31 12:10:31

标签: ruby-on-rails sorcery

我在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  

我的控制器代码
应用程序/控制器/ 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

我的更新表格
应用程序/视图/用户/ 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 %>

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

2 个答案:

答案 0 :(得分: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。因此,在那些注册时,只需要密码验证。

在编辑过程中,当然用户将是现有用户/ new_record?将返回false。因此,将跳过密码验证。

第二种方式:

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,则在编辑/更新期间将跳过密码验证。

我希望这两种方式都可以帮到你:)

答案 1 :(得分:1)

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

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

其中:crypted_passwordsorcery_config.crypted_password_attribute_name的值。

目前Simple Password Authentication巫术维基文章中指出的这种验证条件。