2012-01-07 71 views
2

我的用戶模型具有軌update_attributes方法

validates :password, :presence => true, 
           :confirmation => true, 
           :length => {:within => 6..40} 

和用戶的控制器上我的更新動作

def update 
     @user = User.find(params[:id]) 
     if @user.update_attributes(params[:user]) 
      flash[:success] = "Profile updated." 
      redirect_to @user 
     else 
      @title = "Edit user" 
      render 'edit' 
     end 
    end 

我編輯的看法是

<%= form_for(@user) do |f| %> 
<%= render 'shared/error_messages', :object => @user.errors%> 
<div class="field"> 
    <%= f.label :name %><br /> 
    <%= f.text_field :name %> 
</div> 
<div class="field"> 
    <%= f.label :email %><br /> 
    <%= f.text_field :email %> 
</div> 
<div class="field"> 
    <%= f.label :password %> <br /> 
    <%= f.password_field :password %> 
</div> 
<div class="field"> 
    <%= f.label :password_confirmation, "Confirmation" %> <br /> 
    <%= f.password_field :password_confirmation %> 
</div> 
<div class="actions"> 
    <%= f.submit "Update" %> 
</div> 

的問題是,我只想更新模型的特定屬性,而不是輸入密碼每次。如果我沒有輸入密碼(和確認),我會得到驗證錯誤)

如何解決這種情況?

+0

我剛剛看到http://stackoverflow.com/questions/7073720/ruby-on-rails-tutorial-how-to-edit-user-information-without-confirming-the-pass我會測試它並回報 – 2012-01-07 10:29:49

+0

鏈接上的解決方案不工作... – 2012-01-07 16:42:39

回答

1

嘗試下一個驗證規則

驗證:密碼:存在=>真,如果=>拉姆達{new_record? || !password.nil? }

0

您可以使用attr_protectedupdate_attributes中排除某些字段。請參閱doc。更好的方法是使用attr_accessible來列出可以通過批量分配更新的屬性。

+0

如果我使用attr_protected,用戶將無法首先輸入密碼 – 2012-01-07 19:01:14

相關問題