2014-02-15 53 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

的更新動作
相關問題