xps15z
xps15z

Reputation: 1829

Select avatar from uploaded files

I have carrierwave installed and users can upload photos. How do I set so users don't have to upload a avatar file, but instead can select from their uploaded photos which one will be represented as their avatar? For example when you're on Facebook, click on one of your photos, click the 'Options' link and it shows you 'Make profile picture'. That image will then become your avatar, or picture that is used throughout Facebook. I am looking for the same thing.

Gallery Controller:

 def index
    @galleries = Gallery.all
  end

  def show
    @gallery = Gallery.find(id_params)
  end

  def new
    @gallery = Gallery.new
  end

  def create
    @gallery = Gallery.new(gallery_params)
    if @gallery.save
      flash[:notice] = "Created gallery."
      redirect_to @gallery
    else
      render :action => 'new'
    end
  end

  def edit
    @gallery = Gallery.find(id_params)
  end

  def update
    @gallery = Gallery.find(id_params)
    if @gallery.update_attributes(gallery_params)
      flash[:notice] = "Updated gallery."
      redirect_to gallery_url
    else
      render :action => 'edit'
    end
  end

  def destroy
    @gallery = Gallery.find(id_params)
    @gallery.destroy
    flash[:notice] = "Gallery deleted."
    redirect_to galleries_url
  end

  private


   def gallery_params
     params.require(:user).permit(:name)
   end

   def id_params
     params.require(:id).permit(:name)
   end

end

Photo 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 edit
    @photo = Photo.find(params[:id])
  end

  def update
    @photo = Photo.find(params[:id])
    if @photo.update_attributes(paramas[: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
end

Upvotes: 1

Views: 384

Answers (1)

Farley Knight
Farley Knight

Reputation: 1793

Here's an example of what I might do

class UserAvatarController < ApplicationController
  def edit
    @gallery = current_user.gallery
    # render gallery of photos for user to choose
  end

  def update
    if params[:photo_id].present?
      current_user.update_attributes avatar_id: params[:photo_id]
    else
      flash[:error] = "No photo selected"
      render action: "edit"
    end
  end
end

Upvotes: 1

Related Questions