我安装了CarrierWave gem。没有画廊,因为我设置了照片属于用户而不是画廊。
我在“照片”表格中添加了avatar
列。其他列是:id,created_at,updated_at,image,name,user_id
问题是如何设置操作,以便用户点击“制作个人资料图片”,它会对avatar
列进行更改?这应该通过单击图像的缩略图版本或具有文本覆盖来完成。
我的意思的一个例子:
用户Z将四张照片上传到他们的个人资料中。用户Z访问他们的个人资料并选择他们上传的一张照片作为他们的个人资料图片(头像)。
class PhotosController < ApplicationController
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(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
def avatar
@photo = Photo.find params[:photo_id]
current_user.default_photo = @photo
redirect_to '/profile'
end
end
查看(在个人资料中显示拇指照片):
<div class="parent-container">
<% @user.photos.each do |photo| %>
<%= link_to image_tag(photo.image_url(:thumb)), photo.image_url%>
<% end %></div></p>
答案 0 :(得分:2)
您有User
而User
有Photos
,其中一个可能是Avatar
...
我建议你做的是在avatar_id
上User
,以及如下关系:
class User < ActiveRecord::Base
has_many :photos
belongs_to :avatar, class_name: 'Photo'
end
然后在controller
中,如果您希望添加新的action
,则会如此:
class PhotosController < ApplicationController
...
def avatar
if current_user.update_attribute(:avatar_id, params[:id])
#set flash success
else
#set flash fail
end
redirect_to(current_user) # However you plan to handle this...
end
...
end
(您可能想要使用新控制器的原因是维持“DRY”)
我认为你会有一个route
成员:
resources :photos do
member do
post :avatar
end
end
和action
一样:
button_to('Set as Avatar', [:avatar, @photo])
然后你在视图中引用它:
@user.avatar.image_url(:thumb)
这应该可以解决问题。
答案 1 :(得分:0)
您可以执行以下操作,以便渲染可用照片库并允许用户为其DP /头像/个人资料图片选择一个
class UserAvatarController < ApplicationController
def edit
@gallery = current_user.gallery
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