首页 文章

Rails:从表格中选择头像

提问于
浏览
1

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

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

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

在他们的用户配置文件中,我将有一个字段,我假设存储avatar_id - 但从那里我被卡住了 - 我希望他们看到头像的图库并做出选择来填充该字段 . 我对宝石持开放态度 - 但大多数看起来比我需要的更复杂 .

任何援助将不胜感激 .

1 回答

  • 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
    

    Profiles 图片模型将用户与头像链接在一起 .

    由于用户只能从一组头像中进行选择,因此您只需将管理员创建为头像 . 只需将头像图像放在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
    

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

相关问题