Question

In the rails application I am developing, I want the to give the end users the ability to select an avatar. Nothing unusual here.

Unfortunately, I have found numerous articles, posts and gems about the uploading and selection of images (example: Is there any rails gem for avatar selection? | http://rubygems.org/gems/paperclip ) but what I want is for them to select from an 'Avatar' table in my database. I do not want them to be able to upload anything. The Avatars which they can select from will be created for them.

My thought is that the Avatar table would have two columns: id and url_path.

In their user profile I would have a field I assume to store the avatar_id -- but from there I am stuck --- I want them to see the gallery of avatars and make a selection to populate that field. I am open to a gem -- but most seem more complex than I need.

Any assistance would be appreciated.

Was it helpful?

Solution

Here's some input to push you in the right direction. I don't think you need a gem for this.

You need three models:

class User < ActiveRecord::Base
  has_one :avatar, through: :profile_picture
  has_one :profile_picture
  # change both associations to has many if a user can have multiple avatars
end

class Avatar < ActiveRecord::Base
  has_one :profile_picture
  # attribute: filename
end

class ProfilePicture < ActiveRecord::Base
  belongs_to :user
  belongs_to :avatar
  # attributes: user_id and avatar_id
end

The profile picture model links users with avatars.

Since the user will only be able to choose from a set of avatars, you simply create the avatars as admin. Just put avatar images in assets/images/avatars and create the avatar records in the database yourself:

# assuming an avatar's filename is avatar.png
Avatar.create(filename: 'avatar.png')
# and make sure you have such an image in assets/images/avatars

Then, assuming you have a page where you render all avatars as, e.g., linked images as preview that users can click on to select one, you could simply link those images to a ProfilePicturesController's create action. You will need the following route

resources :profile_pictures, only: [ :create ]

and the following erb code for your images for the user to choose from:

<% Avatar.all.each do |a| %>
  <%= link_to image_tag("assets/images/avatars/#{a.filename}"), profile_pictures_path(avatar_id: a.id), method: :post %>
<% end %>

and the following controller code:

class ProfilePicturesController < ActionController::Base
  def create
    ProfilePicture.create(
      avatar_id: params[:avatar_id],
      user_id: current_user.id         # or however you retrieve the current user
    )
    flash[:notice] = 'Avatar updated.' # just a suggestion
    redirect_to :back                  # just a suggestion
  end
end

Haven't actually tried any of this, so let me know if it works.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top