开发者

Paperclip: Stay put on edit

开发者 https://www.devze.com 2023-02-02 06:01 出处:网络
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_

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.f开发者_如何学JAVAind(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


You shouldn't need @accommodation.build_photo anywhere else than in new action.

0

精彩评论

暂无评论...
验证码 换一张
取 消