Ruby   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了ruby-on-rails – 编辑具有以前成功上传图像的记录时,如何在编辑时不必重新上传?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用Carrierwave,Fog将图像上传到S3.

问题是,当我去编辑一个记录时,“文件”和& “照片”字段自动变为空白.因此,如果我想保留记录中的图像或文件,我必须重新上传它.

否则,会发生什么是上传的文件/图像消失了.我甚至不确定它是否从S3中删除,但与我在db中的记录的关联消失了.

这是我的Post模型的SimpleForm _form.html.erb partial:

<%= simple_form_for(@post,html: {Class: 'form-horizontal' }) do |f| %> 
    <%= f.error_notification %>
    <%= f.input_field @R_850_6964@,placeholder: "Enter title"  %>
    <%= f.input_field :body,id: "body-field",placeholder: "Provide all the facts." %>
    <%= f.input_field :photo %>
    <%= f.input_field :file %>
    <%= f.button :submit,class: "btn btn-pri@R_197_11035@ pull-left" %>
<% end %>

这是我的PhotoUploader

class PhotoUploader < CarrierWave::Uploader::Base
  include CarrierWave::rR_166_11845@agick
  storage :fog

  include CarrierWave::MimeTypes
  process :set_content_type

  def store_dir
    "images/#{model.class.to_S.UnderscorE}/#{mounted_as}/#{model.iD}"
  end

    version :main_thumb_mobile do
      process :resize_to_fit => [52,52]
    end

    version :main_thumb do
      process :resize_to_fit => [150,150]
    end

    version :post_thumb do
      process :resize_to_fit => [200,200]
    end

    version :large do
      process :resize_to_limit => [400,400]
    end

  def extension_white_list
    %w(jpg jpeg gif png)
  end
end

这是我的FileUploader

class FileUploader < CarrierWave::Uploader::Base
  storage :fog
  def store_dir
    "files/#{model.class.to_S.UnderscorE}/#{mounted_as}/#{model.iD}"
  end

  def extension_white_list
    %w(pdf doc docx xls xLSX ppt pptx txt mp4 m4v mov avi mkv mp3 wav)
  end    
end

这是我的帖子的架构:

# == scheR_166_11845@a Information
# truncated for brevity
# Table name: posts
#
#  id                    :Integer          not null,pri@R_197_11035@ key
#  title                 :text
#  photo                 :string(255)
#  body                  :text
#  user_id               :Integer
#  file                  :string(255)

编辑1

这是我的Post.rb:

# == scheR_166_11845@a Information
#
# Table name: posts
#
#  id                    :Integer          not null,pri@R_197_11035@ key
#  title                 :text
#  photo                 :string(255)
#  body                  :text
#  created_at            :@R_489_7538@me
#  updated_at            :@R_489_7538@me
#  user_id               :Integer
#  ancestry              :string(255)
#  file                  :string(255)
#  status                :Integer          default(0)
#  slug                  :string(255)
#  publication_status    :Integer          default(0)
#  has_eyewitness        :Boolean          default(false)
#  youtube_embed_code    :text
#  soundcloud_embed_code :text
#

class Post < ActiveRecord::Base
  has_ancestry
  belongs_to :user
  resourcify
  enum status: [ :unconfirmed,:corroborated,:confirmed ]
  enum publication_status: [ :unpublished,:published ]
  extend FriendlyId
  friendly_id @R_850_6964@,use: [:slugged,:history,:finders]

  attr_accessor :country

  mount_uploader :photo,PhotoUploader
  mount_uploader :file,FileUploader

  validates_presence_of :body
  validates_length_of :body,maximum: 150,too_long: 'The report must be less than 150 words.',tokenizer: ->(str) { str.scan(/\w+/) }
  validates_length_of @R_850_6964@,maximum: 7,too_long: 'The title must be less than 7 words.',tokenizer: ->(str) { str.scan(/\w+/) }

  def publish
    published!
  end

  def unpublish
    unpublished!
  end

  def is_published?
    if self.published?
      "yes"
    else
      "no"
    end
  end      
end

编辑2

我将f.input_field:我的表单中的照片更改为f.file_field:照片按照jaspreet的建议,它仍然无法正常工作.这是我更新请求的日志:

Started PATCH "/posts/ognr-takes-over-amcham-6a6f01ba-a9f9-44d5-924a-72f666f20ca8" for 127.0.0.1 at 2014-12-28 13:51:38 -0500
Processing by PostsController#update as HTML
  Parameters: {"utf8"=>"✓","authenticity_token"=>"S7FOq956fox6XYpar7Yd6V7AL+bwypQQxZktjHW3PNc=","post"=>{"parent_id"=>"","status"=>"unconfirmed","publication_status"=>"unpublished","title"=>"OGNR takes over AMCHAM","body"=>"OGNR storms the rerl.","has_eyewitness"=>"1","youtube_embed_code"=>"","soundcloud_embed_code"=>""},"commit"=>"update Post","id"=>"ognr-takes-over-amcham-6a6f01ba-a9f9-44d5-924a-72f666f20ca8"}
  User Load (1.7ms)  SELECT  "users".* FROM "users"  WHERE "users"."id" = 1  ORDER BY "users"."id" ASC LIMIT 1
   (1.2ms)  SELECT COUNT(*) FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND (((roles.name = 'admin') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)))  [["user_id",1]]
   (6.4ms)  SELECT COUNT(*) FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND (((roles.name = 'editor') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)))  [["user_id",1]]
   (0.2ms)  BEGIN
  Post Exists (1.0ms)  SELECT  1 AS one FROM "posts" INNER JOIN "friendly_id_slugs" ON "friendly_id_slugs"."sluggable_id" = "posts"."id" AND "friendly_id_slugs"."sluggable_type" = 'Post' WHERE ("posts"."id" IS NOT NULL) AND "posts"."slug" = 'ognr-takes-over-amcham' LIMIT 1
  SQL (0.6ms)  INSERT INTO "posts" ("body","created_at","has_eyewitness","slug","soundcloud_embed_code","title","updated_at","youtube_embed_code") VALUES ($1,$2,$3,$4,$5,$6,$7,$8) RETURNING "id"  [["body","OGNR storms the rerl."],["created_at","2014-12-28 18:51:39.183091"],["has_eyewitness","t"],["slug","ognr-takes-over-amcham-cd491a8e-9a4e-4d5e-b13a-898de4adf135"],["soundcloud_embed_code",""],["title","OGNR takes over AMCHAM"],["updated_at",["youtube_embed_code",""]]
  FriendlyId::Slug Load (0.5ms)  SELECT  "friendly_id_slugs".* FROM "friendly_id_slugs"  WHERE "friendly_id_slugs"."sluggable_id" = $1 AND "friendly_id_slugs"."sluggable_type" = $2  ORDER BY "friendly_id_slugs".id DESC LIMIT 1  [["sluggable_id",43],["sluggable_type","Post"]]
  SQL (0.4ms)  deletE FROM "friendly_id_slugs" WHERE "friendly_id_slugs"."sluggable_id" = $1 AND "friendly_id_slugs"."sluggable_type" = $2 AND "friendly_id_slugs"."slug" = 'ognr-takes-over-amcham-cd491a8e-9a4e-4d5e-b13a-898de4adf135'  [["sluggable_id","Post"]]
  SQL (0.4ms)  INSERT INTO "friendly_id_slugs" ("created_at","sluggable_id","sluggable_type") VALUES ($1,$4) RETURNING "id"  [["created_at","2014-12-28 18:51:39.242475"],["sluggable_id","Post"]]
   (2.6ms)  COMMIT
Redirected to http://localhost:3000/posts/ognr-takes-over-amcham-cd491a8e-9a4e-4d5e-b13a-898de4adf135
Completed 302 Found in 372ms (ActiveRecord: 17.3ms)

编辑3

PostController#update看起来像这样

class PostsController < ApplicationController
  load_and_authorize_resource

  def update
    respond_to do |format|
      if @post.update(post_params)
        format.html { redirect_to @post,notice: 'Report was successfully updated.' }
        format.json { render :show,status: :ok,LOCATIOn: @post }
      else
        format.html { render :edit }
        format.json { render json: @post.errors,status: :unprocessable_entity }
      end
    end
  end

编辑4

解决方法

您需要使用上传图像的输入字段来显示图像名称,并使用javascript函数在输入字段中显示文件名,如下所示:
<%= text_field_tag 'file_name',"#{@post.photo_file_name}",{disabled: true,class: 'browse-input form-control'} %>
<%= f.input_field :photo %>
:javascript
  $("#post_photo").change(function () {
      $("#file_name").val(this.value.replace(/^.*[\\\/]/,''));
  });

并且您可以使用相同的代码上传文件.

用于防止重新上传未更改的照片

您可以使用changed?方法检查照片是否更改,如下所示:

def update
  if @post.photo && !@post.photo.changed?
     @post.update(post_update_params_without_photo)
  end
end
# Example method,don't forgot set the necessary attributes
def post_update_params_without_photo
  params.require(:post).permit(@R_850_6964@)
end

说明:此代码仅更新已更改的属性,即(标题,状态等).

大佬总结

以上是大佬教程为你收集整理的ruby-on-rails – 编辑具有以前成功上传图像的记录时,如何在编辑时不必重新上传?全部内容,希望文章能够帮你解决ruby-on-rails – 编辑具有以前成功上传图像的记录时,如何在编辑时不必重新上传?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。