Add Default Image with Attachment_fu Plugin

Hi Guys,

Hope you all are fine and doing good. My Run Time Experiences bringing more and more posts.
Last Week I was stuck in a Big problem. I am using attachment_fu in my application. Although its a great plugin for file uploading. But I faced couple of problems like :
I m taking example of User_Profile model so there is a user_profiles table in the Db.

(1) Suppose If user left uploaded_data field blank, Next time when user updates the table value and this time also he/she left the field blank, then the Plugin shows me an error.

(2) When User left the uploaded_data field blank while creating user_profile and then try to delete his/her profile. The Plugin gives error something like this :

Can’t Convert nil to String

Now there are two ways to solve this:

(1)  Suppose your user model has_one user_profile. Then in your models/user.rb you can write something like this :

User.rb
has_one :user_profile, :dependent => :destroy

This will work for most of the cases but suppose if you want that if user has left the field blank there should be a default image which would go into the database. So for this in your model user_profile.rb write a method.

def add_default_image
self.content_type = ‘image/png’
self.filename = ‘personal-256.png’
self.temp_path = “#{RAILS_ROOT}/public/images/personal-256.png”
end

make sure that this image is present in your images folder.

Now you need to validate if params[:uploaded_data] is blank or not, suppose my action comes to create method, so do something like this :

def create
@user_profile = UserProfile.new(params[:user_profile])
if params[:user_profile][:uploaded_data].blank?
params[:uploaded_data] = @user_profile.add_default_image
@user_profile.save!
redirect_to(“Some Action”)
flash[:notice] = “Profile has been saved..”
else
if @user_profile.save
redirect_to(Some Action)
flash[:notice] = “Your contact has been saved successfully”
else
render :action => ‘new’
flash[:error] = “There is some problem saving the user”
end
end
end

Your Image should appear to you even if you left the params of uploaded_data blank. I think basics of attachment_fu you all can handle.

Cheers 🙂

Advertisement