Users and Photos - Is this the best way?

Hi,

I have a user and photo model where a user has one photo (using
attachment_fu).

I have copied my user actions for create and update below, and I was
wondering if someone could suggest a better method. I’m just not sure
this is the best way to do this…

def create
@user = User.new(params[:user])
#Create a new photo if the info is sent
if !params[:photo][:uploaded_data].blank?
@user.photo = Photo.create(params[:photo])
end
@user.save!
self.current_user = @user
redirect_back_or_default(’/’)
flash[:notice] = “Thanks for signing up!”
rescue ActiveRecord::RecordInvalid
render :action => ‘new’
end

and

def update
@user = User.find(params[:id])
respond_to do |format|
if @user.update_attributes(params[:user])
if !params[:photo][:uploaded_data].blank?
#Create new photo for the user or find the existing one
@photo = @user.photo ||= Photo.new
@photo = @user.photo.build(params[:photo])
@photo.save
end
flash[:notice] = ‘Your account was successfully updated.’
format.html { redirect_to users_url }
format.xml { head :ok }
else
format.html { render :action => “edit” }
format.xml { render :xml => @user.errors.to_xml }
end
end
end

I would find any help / feedback useful.

Thanks!

If anyone could also give some tips on how to delete the old
attachment (photo) once a new one is created I would appreciate it.

I keep getting an error message when I try to delete the old
attachment before creating the new one regarding access to frozen
hashes.

Thanks.

Incase anyone is interested / need this, this is the final update
action I have:

def update
@user = User.find(params[:id], :include => :photo)
respond_to do |format|
if @user.update_attributes(params[:user])
# If there is photo data, create the new photo
if !params[:photo][:uploaded_data].blank?
# Look to see if a previous photo exists
@old_photo = Photo.find_by_user_id(@user.id) if
params[:photo][:uploaded_data]
if @old_photo.nil?
@photo = @user.photo ||= Photo.new
@photo = @user.photo.build(params[:photo])
@photo.save
else
@photo = @user.photo
@photo.update_attributes(params[:photo])
end
end
flash[:notice] = ‘Your account was successfully updated.’
format.html { redirect_to users_url }
format.xml { head :ok }
else
format.html { render :action => “edit” }
format.xml { render :xml => @user.errors.to_xml }
end
end
end

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs