Reputation: 2924
I am using the CarrierWave gem and I have a avatar_id
column on the Users table and a Photos table that has a id
and user_id
column. Is there a way to setup so the first photo uploaded by a User will be assigned to their avatar_id
?
For example I sign up as User 56. I upload my first photo (id 89) and my avatar_id
column updates with id 89.
Photos Controller:
def new
@photo = Photo.new
end
def create
@photo = Photo.new(params[:photo])
@photo.user = current_user
if @photo.save
flash[:notice] = "Successfully created photos."
redirect_to :back
else
render :action => 'new'
end
end
def resize(width, height, gravity = 'Center')
manipulate! do |img|
img.combine_options do |cmd|
cmd.resize "#{width}"
if img[:width] < img[:height]
cmd.gravity gravity
cmd.background "rgba(255,255,255,0.0)"
cmd.extent "#{width}x#{height}"
end
end
img = yield(img) if block_given?
img
end
end
def edit
@photo = Photo.find(params[:id])
end
def update
@photo = Photo.find(params[:id])
if @photo.update_attributes(params[:photo])
flash[:notice] = "Successfully updated photo."
redirect_to @photo.gallery
else
render :action => 'edit'
end
end
def destroy
@photo = Photo.find(params[:id])
@photo.destroy
flash[:notice] = "Successfully destroyed photo."
redirect_to @photo.gallery
end
def avatar
if current_user.update_attribute(:avatar_id, params[:id])
flash[:notice] = "Successfully made Avatar."
else
flash[:notice] = "Avatar failed"
end
redirect_to(current_user)
end
end
Upvotes: 0
Views: 85
Reputation: 80140
This is starting to get more complicated than you probably want to dump in your controllers (start looking to service objects to help), but here's what you'll want to do:
# photo created above
photo.user = current_user
if photo.save
if current_user.photos.size <= 1
current_user.avatar = photo
end
flash[:success] = '...'
# ...
end
Another approach is to simply check to see if avatar is set yet, which is probably more appropriate, but I wanted to show you what you were asking for first.
current_user.avatar = photo if current_user.avatar.blank?
Upvotes: 1