2012-02-13 36 views
-2

我在更新圖像(用戶的頭像)時遇到問題。我正在使用CarrierWave並有兩種型號:profileuser爲什麼我無法使用CarrierWave更新圖像?

user#show頁面上,我有一個表格profile,其中我有file_field。配置文件屬於用戶。這裏是表格:

<%= form_for @user.profile do |f| %> 
     <%= f.file_field :avatar %><br/> 
     <%= f.submit "Change Avatar" %><br/> 
     <% end %> 

提交後,圖像沒有更新。在服務器日誌中我看到:

Processing by ProfilesController#update as HTML Parameters: 
{"utf8"=>"✓", 
"authenticity_token"=>"lHbhHK9SLIiTUuBJAAUyz0CSSC1tUhbE0oD2An2QEEY=", 
"profile"=>{"avatar"=>#<ActionDispatch::Http::UploadedFile:0x007fa60ff43b40 
@original_filename="P1010056.JPG", @content_type="image/jpeg", 
@headers="Content-Disposition: form-data; name=\"profile[avatar]\"; 
filename=\"P1010056.JPG\"\r\nContent-Type: image/jpeg\r\n", 
@tempfile=#<File:/var/folders/kq/gjn7ljfx1wx418ptwnbb46vr0000gn/T/RackMultipart20120213-2399-sm0m9c>>}, 
"commit"=>"Change Avatar", "id"=>"1"} 

這是我的個人資料更新動作:

def update 
    @profile = current_user.profile 
    if @profile.update_attributes(params[:profile]) 
    redirect_to user_path(current_user) 
    end 
end 

我做錯了嗎?

+0

看起來你修剪'「阿凡達」 =>#>'什麼類是價值?另外,在你的模型中,你是否告訴它使用一些東西來處理上傳的文件? – 2012-02-13 01:51:32

+0

我應該怎麼做才能處理上傳的文件,如果我想更改其他模型字段,如:名稱和其他,它們也不會更改 – Pavel 2012-02-13 08:32:31

+1

「未更新」是什麼意思?你在哪裏存儲圖像?如果你去那裏,你看到它嗎? – 2012-02-13 11:57:39

回答

4

請確保您有在形式設置爲true,多屬性:

<%= form_for @user.profile, :html => {:multipart => true} do |f| %> 
    <%= f.file_field :avatar %><br/> 
    <%= f.submit "Change Avatar" %><br/> 
<% end %> 

你是否還檢查了,如果你已經設置attr_accessible在模型中的分身屬性?您的模型可能沒有啓用批量分配。請確保你在你的Profile模型有這樣的:

attr_accessible :avatar, :avatar_cache, :remove_avatar

+1

我已經添加了多部分和attr_accessible,但它does not幫助 – Pavel 2012-02-13 08:29:43

+0

@Dia你不需要包含'multipart'爲'form_for',這個選項是對於簡單的表單和'form_tag',看看http://guides.rubyonrails.org/form_helpers.html中的第5點 – ImranNaqvi 2016-01-17 22:54:35