2014-02-15 57 views
0

我有设置窗体。我想让如果密码字段为空,更新其他属性。 另外我正在使用设计。有没有一些有用的方法可以帮助我呢?使用和不使用密码更新用户设置。导轨

form.html.erb

<%= form_for(@user, :url => url_for(:controller => 'settings', :action => 'update')) do |f| %> 

    <%= f.label :email, 'Email' %> 
    <%= f.email_field :email %> 

    <%= f.label :mobile, 'Mobile' %> 
    <%= f.phone_field :mobile %> 

    <%= f.label :current_password, "Current password" %> 
    <%= f.password_field :current_password %> 

    <%= f.label :password, "New Password" %> 
    <%= f.password_field :password, :autocomplete => "off" %> 

    <%= f.label :password_confirmation, "Confirm New Password" %> 
    <%= f.password_field :password_confirmation %> 

    <%= f.submit "Update" %>     
<% end %> 

user.rb

validates :password, length: {minimum: 4}, on: :update, allow_blank: true 

settings_controller.rb

def update 
    @user = current_user 

    if @user.update_attributes(user_params) 
     sign_in(@user, :bypass => true) 
     flash[:success] = "Settings were successfully updated" 

     respond_to do |format| 
      format.html {redirect_to :action=> :show} 
     end 
    else 
     flash[:fail] = "Settings **was not updated**" 
     respond_to do |format| 
      format.html {render :action => :show } 
     end 
    end 
    end 
+0

有一个特殊的方法f或'update_without_password' – devanand

+0

@devanand谢谢你的回答,但不幸的是这对我不起作用。我的表单包含密码。如果用户填写此字段,我想更新它。 – MikeAndr

回答

1

使用THI S:

def update 
    # For Rails 4 
    account_update_params = devise_parameter_sanitizer.sanitize(:account_update) 
    # For Rails 3 
    # account_update_params = params[:user] 

    # required for settings form to submit when password is left blank 
    if account_update_params[:password].blank? 
     account_update_params.delete("password") 
     account_update_params.delete("password_confirmation") 
    end 

    @user = User.find(current_user.id) 
    if @user.update_attributes(account_update_params) 
     set_flash_message :notice, :updated 
     # Sign in the user bypassing validation in case his password changed 
     sign_in @user, :bypass => true 
     redirect_to after_update_path_for(@user) 
    else 
     render "edit" 
    end 
    end 

这是从色器件维基无耻的复制粘贴,它包含了很多的,你可以参考有用的信息 - wiki

0

我也使用设计并在管理命名空间有users_controller继承自application_controller,因为我想保持管理和用户部分分离。 下面的东西适合我。

在用户模型

验证:密码,:password_confirmation,存在:真,上:创建

在控制器

def update # ..... @user.update_without_password(users_params) # ...... end

的更新动作
相关问题