Rails:从表格中选择头像

时间:2013-12-28 21:22:03

标签: ruby-on-rails user-profile avatar

在我正在开发的rails应用程序中,我希望让最终用户能够选择一个头像。这里没什么不寻常的。

不幸的是,我发现了很多关于图片上传和选择的文章,帖子和宝石(例如:Is there any rails gem for avatar selection? | http://rubygems.org/gems/paperclip),但我想要的是让他们从“阿凡达”中选择我的数据库中的表。我不希望他们能够上传任何东西。他们可以选择的头像将为他们创建。

我的想法是Avatar表有两列:id和url_path。

在他们的用户个人资料中,我会假设存储avatar_id的字段 - 但是从那里我被卡住了 - 我希望他们看到化身库并选择填充该字段。我对一颗宝石持开放态度 - 但大多数看起来比我需要的更复杂。

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:2)

这是一些推动你朝着正确方向前进的输入。我认为你不需要宝石。

您需要三种模式:

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

个人资料图片模型将用户与头像链接。

由于用户只能从一组头像中进行选择,因此您只需将头像创建为管理员即可。只需将头像图像放在assets / images / avatars中,然后自己在数据库中创建头像记录:

# 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

然后,假设您有一个页面,您将所有头像渲染为,例如,链接图像作为预览,用户可以单击以选择一个,您可以简单地将这些图像链接到ProfilePicturesController的创建操作。您将需要以下路线

resources :profile_pictures, only: [ :create ]

以及您的图片的以下erb代码供用户选择:

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

和以下控制器代码:

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

实际上没有尝试过这些,所以请告诉我它是否有效。