【问题标题】:Add ProfileImage from users previously uploaded photos从用户之前上传的照片中添加 ProfileImage
【发布时间】:2013-10-09 19:58:35
【问题描述】:

我尝试过这样做,但没有成功。考虑到选择默认照片是每个社交网络的选项,也没有任何帖子涵盖此内容,这很奇怪。我有 CarrierWave gem,我想对其进行设置,以便用户可以从他们已经上传的照片中选择他们的 ProfileImage(默认图像)。这张照片将在网站范围内使用。这就像拥有一个头像,但是那里的文章只显示如何上传头像,而不是从您上传的照片中选择头像。我相信这对其他人会有所帮助,因为这是一个常见功能。

照片控制器:

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 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
end

用户模型:

# It is setup so no gallery is created, and photos are associated with the user.

  private
  def setup_gallery
     Gallery.create(user: self)
   end

照片模型:

  attr_accessible :title, :body, :gallery_id, :name, :image, :remote_image_url
  belongs_to :gallery
  has_many :gallery_users, :through => :gallery, :source => :user
  belongs_to :user
  mount_uploader :image, ImageUploader

  LIMIT = 5

  validate do |record|
    record.validate_photo_quota
  end

  def validate_photo_quota
    return unless self.user
    if self.user.photos(:reload).count >= LIMIT
      errors.add(:base, :exceeded_quota)
    end
  end
end

【问题讨论】:

    标签: ruby-on-rails carrierwave


    【解决方案1】:

    您可以将用户模型设置为直接链接到默认照片。

    class User < ActiveRecord::Base
      belongs_to :default_photo, :class_name => "Photo"
    end
    

    您还需要在 users 表中添加一个 default_photo_id 列。

    然后提供一个界面,允许用户浏览他们所有的照片。在 UI 中,您可以有一个显示“设为默认值”(或其他任何内容)的按钮,当用户单击该按钮时,它会触发如下所示的控制器操作:

    def choose_default_photo
      @photo = Photo.find params[:photo_id]
      current_user.default_photo = @photo
      redirect_to '/profile' # or wherever you wan to send them
    end
    

    然后,每当您需要为您刚刚使用的默认照片引用模型时:

    current_user.defaut_photo
    

    【讨论】:

    • 无需从数据库中提取@photo记录,只需设置default_photo:current_user.default_photo_id = params[:photo_id]
    【解决方案2】:

    您还应该注意销毁默认图像时的情况。如果需要,您应该将 default_photo_id 设置为 nil 或任何其他照片。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-02
      • 2014-02-02
      • 1970-01-01
      • 2018-06-01
      • 1970-01-01
      • 2015-07-24
      • 2013-06-28
      • 1970-01-01
      相关资源
      最近更新 更多