2010-10-14 59 views
0

我是新來的rails,並有一個簡單的問題。在Rails中部分更新模型3

我有一個滑軌模型:

class User < ActiveRecord::Base 

    attr_accessor :password 
    attr_accessible :name, :email, :password, :password_confirmation, :description 

    email_regex = /\A[\w+\-.][email protected][a-z\d\-.]+\.[a-z]+\z/i 

    validates :email, :presence => true 

    validates :name,  :presence => true 

    validates :password, :presence => true 

    ... 

end 

在我的頁面更新這個模型我有一個包含電子郵件的文本框和名稱的文本框的形式。

在我的控制器我有以下更新方法:

def update 
    @user = User.find(params[:id]) 

    respond_to do |format| 
    if @user.update_attributes(:name => params[:name], :email => params[:email]) 
     flash[:success] = "Profile updated" 
     format.html { redirect_to(@user, :notice => 'User was successfully updated.') } 
     format.xml { head :ok } 
    else 
     @title = "Edit user" 
     format.html { render :action => "edit" } 
     format.xml { render :xml => @user.errors, :status => :unprocessable_entity } 
    end 
    end 
end 

這是一個奇怪的錯誤信息失敗:

undefined method `downcase' for nil:NilClass 

可有人告訴我,我錯了嗎?我知道我在做什麼愚蠢的,但不能制定出它是什麼......

回答

2

如果插入某種輔助方法,可以有條件地觸發驗證。這通常是對多級條目,或部分更新的情況:

class User < ActiveRecord::Base 
    validates :password, 
    :presence => { :if => :password_required? } 

protected 
    def password_required? 
    self.new_record? 
    end 
end 

我真的希望你不是保存密碼明文。這是一個巨大的責任。通常passwordpassword_confirmation是稍後散列和保存的臨時attr_accessor方法。

1

下面一行是錯誤的

@user.update_attributes(params[:name], :email => params[:email]) 

想要的update_attributes哈希值。

@user.update_attributes(:name => params[:name], :email => params[:email]) 

此外,你應該在你的視圖使用form_for幫手讓你的所有用戶屬性在params[:user]散列分組。

+0

道歉...這是一個錯字。我確實有一個哈希 - 我已經更新了這個問題。我也使用form_for幫手。問題是我沒有在窗體上的密碼屬性。如果我嘗試@ user.update_attributes(params [:user]),它會失敗,因爲需要密碼。 – Paul 2010-10-14 18:12:19