开发者

Sinatra/Carrierwave: how to update a record while using an existing image?

开发者 https://www.devze.com 2023-04-11 16:20 出处:网络
My super-simple Sinatra app is a list of notes, and each note has an attached image. I\'ve got a \'put\' route set up that lets me update notes, but unless I re-upload the image, I lose it (note.imag

My super-simple Sinatra app is a list of notes, and each note has an attached image.

I've got a 'put' route set up that lets me update notes, but unless I re-upload the image, I lose it (note.image is set to 'nil' when I submit the form).

Thanks in advance for your help!

Here's my uploader:

class MyUploader < CarrierWave::Uploader::Base
  include CarrierWave::MimeTypes
  process :set_content_type
  storage :fog
end

Here's my Note class:

class Note
    include DataMapper::Resource
    property :id, Serial
    property :image, String, :auto_validation =&开发者_开发知识库gt; false
    property :content, Text, :required => true
    property :created_at, Date
    property :updated_at, Date
    mount_uploader :image, MyUploader                   
end

Here's my 'put' route:

put '/:id' do
  n = Note.get params[:id]
    unless n
      redirect '/', :error => "Can't find that note."
    end
  n.image = params[:image] 
  n.credit = params[:content]
  n.date = params[:date]
  n.updated_at = Time.now
  if n.save
    redirect '/', :notice => 'Note updated successfully.'
  else
    redirect '/', :error => 'Error updating note.'
  end
end

And here's the form I'm using to update notes:

<% if @note %>
  <form action="/<%= @note.id %>" method="post" id="edit" enctype="multipart/form-data">
    <input type="hidden" name="_method" value="put">
    <p><input type="text" name="credit" value="<%=h @note.content %>"></p>
    <p><input type="file" name="image" /></p>
    <br><br>
    <input type="submit">
  </form>
<% else %>
    <p>Note not found.</p>
<% end %>


A simple if check is what you need: if params[image] is nil you skip the n.image = params[:image]

n.image = params[:image] if params[:image]

I use similar approach to create a custom Rails validation check when I work with ActiveRecord models that contain CarrierWave images. Probably it won't be a bad idea to check whether or not n.image isn't nil as well - if it's nil I guess it should be mandatory to upload an image.

0

精彩评论

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

关注公众号