2011-01-19 19 views
3

回形針運行良好,以保存用戶頭像,但我發現更新的問題。Rails 3和回形針更新方法問題

在我看來,如果用戶在模型中保存了一個圖像,它將在文件上傳字段旁邊顯示帶有當前圖像的圖像標籤,以便您可以看到您當前的頭像是什麼。

如果圖像沒有變化,但模型驗證失敗(如no first_name),原始顯示圖像消失,這意味着用戶必須糾正錯誤並重新選擇圖像並提交(更新)或去返回並重新開始,而不會出現錯誤。有任何想法嗎?提前致謝。

繼承人的代碼:

型號

class User < ActiveRecord::Base 

    # Validation 
    validates :first_name, :presence => true 

    # Paperclip 
    has_attached_file :avatar, :styles => { :medium => "300x300>", :thumb => "70x70#" } 

end 

控制器

... 
    # GET /users/1/edit 
    def edit 
    @user = User.find(params[:id]) 
    end 

    # POST /users 
    # POST /users.xml 
    def create 
    @user = User.new(params[:user]) 

    respond_to do |format| 
     if @user.save 
     format.html { redirect_to(@user, :notice => 'User was successfully created.') } 
     format.xml { render :xml => @user, :status => :created, :location => @user } 
     else 
     format.html { render :action => "new" } 
     format.xml { render :xml => @user.errors, :status => :unprocessable_entity } 
     end 
    end 
    end 

    # PUT /users/1 
    # PUT /users/1.xml 
    def update 
    @user = User.find(params[:id]) 

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

查看

<%= form_for @user, :html => {:multipart => true} do |f| %> 
    <div class="row text"> 
    <%= f.label :first_name %> 
    <div class="field"> 
     <%= f.text_field :first_name %> 
    </div> 
    </div> 
    <div class="row"> 
    <%= f.label :avatar %> 
    <div class="field"> 
     <%= image_tag @user.avatar.url(:thumb) %> 
    </div> 
    <div class="field" id="avatar_upload"> 
     <%= f.file_field :avatar %> 
    </div> 
    </div> 
    <div class="row actions"><%= f.submit %> or <%= link_to 'cancel', users_path %>.</div> 
<% end %> 

回答

3

這是由你的形式發送 '零' 的服務器造成的(由於f當你的頁面向你的服務器發送一個POST請求時,由於沒有上傳新的頭像,所以不要填空。短缺隱藏的臨時字段的東西,有幾種方法圍繞此:

  • 客戶端驗證。如果出現任何錯誤,請阻止提交頁面,並且最終不會導致導致丟失圖像的服務器端驗證失敗。
  • 將頭像字段移動到僅處理頭像的同一頁面上的單獨FORM對象。這將確保頁面只在與POST消息相關的虛擬頭像編輯中發送頭像信息。
  • 將頭像上傳/更新功能移至僅處理頭像的完全單獨的頁面。這起作用的理由與上述原因相同。
+0

謝謝!當你說表單對象時,你是指字面意義上的一個單獨的表單或模型,還是你的意思是像在同一個表單中使用fields_for? (對不起,還是相當新的軌道!)感謝您的答覆。 – Mike 2011-01-19 08:01:02