Paperclip: Stay put on edit

Posted by EricR on Stack Overflow See other posts from Stack Overflow or by EricR
Published on 2011-01-05T05:39:12Z Indexed on 2011/01/05 7:53 UTC
Read the original article Hit count: 227

When a user edits something in my application, they're forced to re-upload their image via paperclip even if they aren't changing it. Failing to do so will cause an error, since I validate_presence_of :image. This is quite annoying.

How can I make it so Paperclip won't update its attributes if a user simply doesn't supply a new image on an edit?

The photo controller is fresh out of Rails' scaffold generator. The rest of the source code is provided below.

models/accommodation.rb

class Accommodation < ActiveRecord::Base
  attr_accessible :photo
  validates_presence_of :photo
  has_one :photo
  has_many :notifications
  belongs_to :user
  accepts_nested_attributes_for :photo, :allow_destroy => true
end

controllers/accommodation_controller.rb

class AccommodationsController < ApplicationController
  def index
    @accommodations = Accommodation.all
  end

  def show
    @accommodation = Accommodation.find(params[:id])
    rescue ActiveRecord::RecordNotFound
      flash[:error] = "Accommodation not found."
      redirect_to :home
  end

  def new
    @accommodation = current_user.accommodations.build
    @accommodation.build_photo
  end

  def create
    @accommodation = current_user.accommodations.build(params[:accommodation])
    if @accommodation.save
      flash[:notice] = "Successfully created your accommodation."
      redirect_to @accommodation
    else
      @accommodation.build_photo
      render :new
    end
  end

  def edit
    @accommodation = Accommodation.find(params[:id])
    @accommodation.build_photo
    rescue ActiveRecord::RecordNotFound
      flash[:error] = "Accommodation not found."
      redirect_to :home
  end

  def update
    @accommodation = Accommodation.find(params[:id])
    if @accommodation.update_attributes(params[:accommodation])
      flash[:notice] = "Successfully updated accommodation."
      redirect_to @accommodation
    else
      @accommodation.build_photo
      render :edit
    end
  end

  def destroy
    @accommodation = Accommodation.find(params[:id])
    @accommodation.destroy
    flash[:notice] = "Successfully destroyed accommodation."
    redirect_to :inkeep
  end

end

models/photo.rb

class Photo < ActiveRecord::Base
  attr_accessible :image, :primary
  belongs_to :accommodation
  has_attached_file :image,
    :styles => {
      :thumb=> "100x100#",
      :small  => "150x150>" }
end

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about ruby-on-rails3