Sara Al
Sara Al

Reputation: 115

Paperclip validations are not working

Paperclip is allowing any kind of file upload, and I don't understand. In my app, by default, Users don't have to upload avatars when they register, but they may update their avatar after registration. And the user is able to successfully update their avatar. This all works fine, but the validations are not kicking in.

Validation code below in the 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'}

In my routes I have this:

put 'updateavatar' => 'profile#updateavatar'

This is my form:

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

I don't know why this wouldn't work? It's literally allowing any kind of file to be uploaded when the user updates their profile.

In my profile controller I have this:

  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

Upvotes: 1

Views: 495

Answers (2)

Sara Al
Sara Al

Reputation: 115

current_user.update_attributes(:avatar => params[:user][:avatar]) fixed it

Upvotes: 0

rmagnum2002
rmagnum2002

Reputation: 11421

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

so, using update_attribute will update the object but will skip the validations, using update_attributes will update object with validations.

looks like in controller you should have:

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

Upvotes: 3

Related Questions