如何制作首次上传的照片用户的头像

时间:2014-02-20 15:23:29

标签: ruby-on-rails carrierwave

我正在使用CarrierWave gem,我在Users表上有一个avatar_id列,并且有一个iduser_id列的照片表。有没有办法设置,以便用户上传的第一张照片将被分配到他们的avatar_id

例如,我注册为用户56.我上传了我的第一张照片(ID为89)和我的avatar_id列更新ID为89.

照片控制器:

  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(params[: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
    if current_user.update_attribute(:avatar_id, params[:id])
      flash[:notice] = "Successfully made Avatar."
        else
          flash[:notice] = "Avatar failed"
        end
        redirect_to(current_user)
      end
end

1 个答案:

答案 0 :(得分:1)

这开始变得比你想要在控制器中转储更复杂(开始寻找service objects来帮助),但这是你想做的事情:

# photo created above
photo.user = current_user
if photo.save
  if current_user.photos.size <= 1
    current_user.avatar = photo
  end
  flash[:success] = '...'
  # ...
end

另一种方法是简单地检查是否设置了头像,这可能更合适,但我想先向您展示您的要求。

current_user.avatar = photo if current_user.avatar.blank?