当用户在我的应用程序中编辑某些内容时,他们不得不通过回形针重新上传他们的图像,即使他们没有更改它。如果不这样做将导致错误,因为我validate_presence_of:image。这很烦人。
如果用户只是不在编辑中提供新图像,我怎样才能使Paperclip不会更新其属性?
照片控制器是Rails的脚手架发电机的新鲜产品。其余的源代码如下所示。
模型/ 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
控制器/ 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
模型/ photo.rb
class Photo < ActiveRecord::Base
attr_accessible :image, :primary
belongs_to :accommodation
has_attached_file :image,
:styles => {
:thumb=> "100x100#",
:small => "150x150>" }
end
答案 0 :(得分:1)
除了@accommodation.build_photo
操作之外,您不应该需要new
。