2013-07-01 44 views
1

回形針允許任何類型的文件上傳,我不明白。在我的應用中,默認情況下,用戶在註冊時不必上傳頭像,但他們可以在註冊後更新頭像。用戶能夠成功更新他們的頭像。這一切工作正常,但驗證不是在踢回形針驗證不起作用

驗證在User.rb下面的代碼:

has_attached_file :avatar, :styles => { :profile => "150x150#"}, :default_url => 'missing_:style.png' 

validates_attachment :avatar, presence: true, 
      content_type: { content_type: ['image/jpeg', 'image/jpg', 'image/png'], :message => 'must be a PNG, JPG, or JPEG'}, 
      size: {less_than: 5.megabytes, :message => 'must be less than 5 megabytes'} 

在我的路線我有這樣的:

put 'updateavatar' => 'profile#updateavatar' 

這是我形式:

<%= form_for current_user, :html => { :multipart => true }, :url => {:action => 'updateavatar'} do |form| %> 
    <%= form.file_field :avatar %> 
    <%= form.submit "Upload", class: "btn uploadbtn" %> 
<% end %> 

我不知道爲什麼這不起作用?它實際上允許在用戶更新他們的配置文件時上傳任何類型的文件。

在我的個人資料控制器我有這樣的:

def updateavatar 
    if params[:user][:password].blank? 
    params[:user].delete(:password) 
    params[:user].delete(:password_confirmation) 
    end 
    respond_to do |format| 
    if current_user.update_attribute(:avatar, params[:user][:avatar]) 
     flash[:notice] = 'successfully updated.' 
     format.html { redirect_to profile_index_path } 
    else 
     format.html { render action: "index" } 
    end 
    end 
end 
+0

嘗試使用validates_attachment_content_type作爲一個單獨的驗證。 –

+0

不幸的是,驗證仍在跳過。 –

+0

http://stackoverflow.com/a/12686796/1251349 –

回答

3

update_attribute

# File vendor/rails/activerecord/lib/active_record/base.rb, line 2614 
2614:  def update_attribute(name, value) 
2615:   send(name.to_s + '=', value) 
2616:   save(false) 
2617:  end 

update_attributes方法

# File vendor/rails/activerecord/lib/active_record/base.rb, line 2621 
2621:  def update_attributes(attributes) 
2622:   self.attributes = attributes 
2623:   save 
2624:  end 

因此,使用update_attribute會更新對象,但會跳過驗證,使用update_attributes將更新具有驗證的對象。

看起來像在控制器,你應該有:

if current_user.update_attributes(:avatar, params[:user][:avatar]) ..... 
+0

謝謝。我明白了。 –

+0

謝謝,使用'update_attribute'時請小心,因爲這會跳過驗證。 – SsouLlesS

0

current_user.update_attributes(:化身=> PARAMS [:用戶] [:化身])固定它