回形针宝石上传在 Rails 4 多部分形式中不起作用



我正在尝试设置一个基本表单,能够上传图片,标题和文本正文。我正在使用paperclip 4.2.1宝石和rails 4.2.0.

表单显示正常,我可以输入标题,一些正文文本并选择图片。但是,当我提交表单时,它会跳过 show 方法并返回到索引页面,并且图像不会上传到数据库。

当我提交仅包含标题和正文文本的表单时,它确实显示在 show 方法中。我确实验证了表单页面的源代码显示"enctype="multipart/form-data"。有谁知道我错过了什么??

模式.rb

ActiveRecord::Schema.define(version: 20150310181944) do
create_table "articles", force: :cascade do |t|
    t.string   "title"
    t.text     "text"
    t.datetime "created_at",         null: false
    t.datetime "updated_at",         null: false
    t.string   "image_file_name"
    t.string   "image_content_type"
    t.integer  "image_file_size"
    t.datetime "image_updated_at"
  end

结束

模型 -->文章.rb

class Article < ActiveRecord::Base

  has_attached_file :image
  validates_attachment_content_type :image, content_type: /Aimage/.*Z/
end

查看 --> 新.html.erb

新文章

<%= form_for @article, html: { multipart: true } do |f| %>
  <p>
    <%= f.label :title %><br>
    <%= f.text_field :title %>
  </p>
  <p>
    <%= f.label :text %><br>
    <%= f.text_area :text %>
  </p>
    <p>
    <%= f.label :image %>
    <%= f.file_field :image %>  
    </p>
  <p>
    <%= f.submit %>
  </p>
<% end %>
<%= link_to 'Back', articles_path %>

View -> index.html.erb

<h1>Listing articles</h1>

<%= link_to 'New article', new_article_path %> 
<table>
  <tr>
    <th>Title</th>
    <th>Text</th>
    <th>Image</th>
  </tr>
 <% @articles.each do |article| %>
    <tr>
      <td><%= article.title %></td>
      <td><%= article.text %></td>
      <td><%= image_tag article.image.url %></td>
    </tr>
  <% end %>
</table>

查看 -> 显示.html.erb

<p>
  <strong>Title:</strong>
  <%= @article.title %>
</p>
<p>
  <strong>Text:</strong>
  <%= @article.text %>
</p>
<p>
    <%= image_tag @article.image.url %>
</p>

<%= link_to 'Back', articles_path %>

控制器 --> articles_controller.rb

class ArticlesController < ApplicationController
def index
  @articles = Article.all
end
def show
  @article = Article.find(params[:id])
end

def new
  @article = Article.new
end

def create
  @article = Article.create(article_params)
  @article.save
  redirect_to @article
end
private
  def article_params
    params.require(:article).permit(:title, :text, :image)
  end
end

我对 ruby 和编程很陌生,所以它可能是某个地方的某种类型,但我已经搜索了几天,我不确定为什么图片不会上传。

require 'paperclip/media_type_spoof_detector'
module Paperclip
  class MediaTypeSpoofDetector
    def spoofed?
      false
    end
  end
end

我将上面的代码添加到/config/initializers/paperclip.rb 中,现在我可以很好地上传图片,一切正常!!

从我目前阅读的内容来看,看起来图像附件以某种方式丢失了其扩展名并使欺骗检测器失败。 它可能与文件有关.exe Windows 7 中缺少 Unix 命令,但我尝试从

http://gnuwin32.sourceforge.net/packages/file.htm

并且仍然得到同样的错误,

此处找到了此解决方法:

https://github.com/thoughtbot/paperclip/issues/1429

create方法中存在典型的验证错误。只需将Article.create更改为Article.create!,您将看到错误和回溯。它将帮助您调查和解决问题。

最新更新