【问题标题】:Paperclip image not showing, unpermitted params and routing error回形针图像未显示,未经许可的参数和路由错误
【发布时间】:2017-06-08 05:12:29
【问题描述】:

我正在尝试使用回形针在主页上显示图像,但我有未经许可的参数和路由错误。我尝试了各种解决方案,包括尝试传入一个数组,但我认为这是因为我自己缺乏关于 Rails 的知识。

Parameters: {"utf8"=>"✓", "authenticity_token"=>"Hdw1RzedMZdUE0cPrAXz0fkctQKfW9HX3S5ZwYh4lr0PwTJhHhVwcrglJv5qrMQF3T5YkcJZ9zBiRRRlCoNCNQ==", "document"=>{"doc"=>[#<ActionDispatch::Http::UploadedFile:0x007feaf2db80f0 @tempfile=#<Tempfile:/var/folders/1q/zfrk5kxj1015crsc13jwwrz40000gp/T/RackMultipart20170608-15326-1pcmtgl.jpg>, @original_filename="P1150645.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"document[doc][]\"; filename=\"P1150645.jpg\"\r\nContent-Type: image/jpeg\r\n">]}, "commit"=>"Upload Document"}
Unpermitted parameter: doc
   (1.9ms)  begin transaction
  SQL (2.0ms)  INSERT INTO "documents" ("created_at", "updated_at") VALUES (?, ?)  [["created_at", 2017-06-08 04:47:55 UTC], ["updated_at", 2017-06-08 04:47:55 UTC]]
   (0.8ms)  commit transaction
Redirected to http://localhost:3000/
Completed 302 Found in 46ms (ActiveRecord: 4.8ms)


Started GET "/" for ::1 at 2017-06-08 12:47:55 +0800
Processing by PagesController#home as HTML
  User Load (1.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ?  [["id", 3], ["LIMIT", 1]]
  User Load (0.3ms)  SELECT  "users".* FROM "users" LIMIT ?  [["LIMIT", 1]]
  Rendering pages/home.html.erb within layouts/application
  Document Load (3.1ms)  SELECT "documents".* FROM "documents" ORDER BY created_at
  Rendered documents/_documents.html.erb (56.7ms)
  Rendered documents/_new.html.erb (4.2ms)
  User Load (0.3ms)  SELECT "users".* FROM "users" WHERE ("users"."id" != 3)
  Conversation Load (0.2ms)  SELECT "conversations".* FROM "conversations" WHERE (conversations.sender_id = 3 OR conversations.recipient_id = 3)
  User Load (0.5ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?  [["id", 3], ["LIMIT", 1]]
  User Load (0.5ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?  [["id", 1], ["LIMIT", 1]]
   (0.2ms)  SELECT COUNT(*) FROM "messages" WHERE "messages"."conversation_id" = ?  [["conversation_id", 4]]
  Rendered conversations/_index.html.erb (18.5ms)
  Rendered pages/home.html.erb within layouts/application (141.2ms)
  Rendered shared/_navbar.html.erb (5.2ms)
Completed 200 OK in 426ms (Views: 401.3ms | ActiveRecord: 6.2ms)


Started GET "/docs/original/missing.png" for ::1 at 2017-06-08 12:47:56 +0800

ActionController::RoutingError (No route matches [GET] "/docs/original/missing.png"):

鉴于 document => doc 正在传递给数组,我尝试嵌套参数,即使我将参数留空,它仍然会上传到带有空字段和路由错误的数据库,DocumentsController:

def doc_params
    params.require(:document).permit(:id, :doc)
end

我在这里尝试了多个验证:

class Document < ApplicationRecord
  has_attached_file :doc
  do_not_validate_attachment_file_type :doc
end

我想知道渲染索引是否会导致路由错误,因为我通过重新路由暂时摆脱了但图像仍然为空,documents/_index.html.erb

<div class="container">
    <div class="row around-xs">
        <center>
        <% @documents.each do |document| %>

          <li class="col-xs-3" id="item-grid">
            <%= link_to image_tag(document.doc.url, class: 'media-object', size:"108x152"), document.doc.url, target: '_blank' %>
            <% if @users %>
                <% if current_user.is_admin? %>
                            <%= link_to 'Remove', document_path(document), class: 'btn btn-danger', method: :delete, data: {confirm: 'Are you sure?'} %>
                        <% end %>
                    <% end %> 
                </li>

        <% end %>  
        </center>
    </div>
</div>

home.html.erb

<section id="about" class="about-section">
  <div class="container" id="services">

    <div class="col-lg-8 col-md-offset-2" id="progpos"><h1>My Work</h1></div>

    <%= render 'documents/index' %>
    <br>
    <%= render 'documents/new' %>

  </div>
</section>

请帮忙!谢谢!文件/_new.html.erb

<% if @users %>
  <% if current_user.is_admin? %>

    <%= form_for @document, html: { multipart: true } do |f| %>
      <% if @document.errors.any? %>
        <div id="error_explanation">

          <h2>
            <%= "#{pluralize(@document.errors.count, "error")} prohibited this document from being saved:" %>
          </h2>

          <ul>
            <% @document.errors.full_messages.each do |msg| %>

              <li>
                <%= msg %>
              </li>
            <% end %>

          </ul>
        </div>
      <% end %>

      <div class="form-group" style="width: 20%">
        <%= f.file_field :doc, class: 'form-control', placeholder: "Document", multiple: true %>
      </div>

      <div class="form-group">
        <%= f.submit 'Upload Document', class: 'btn btn-default' %>
      </div>

    <% end %>
  <% end %>
<% end %>

这是整个控制器,我已将文档 /_new.html.erb 编辑为外观:

class DocumentsController < ApplicationController

    def index
        @documents = Document.order('created_at')
    end

    def new
        @document = Document.find(params[:id])
    end

    def create
      @document = Document.new(doc_params)
        if @document.save
            **params[:document][:doc].each do |d| #iterate over multiple attached files     
            @document.create(doc: d)**
        end
            flash[:success] = "The document was added!"
            redirect_to root_path
        else
            render '_new'
        end
    end

    def destroy
    @document = Document.find(params[:id])
    if @document.destroy
      flash[:notice] = "Successfully deleted photo!"
      redirect_to root_path
    else
      flash[:alert] = "Error deleting photo!"
    end
  end

    private

    def doc_params
        params.require(:document).permit(:id, **document: {doc: []}**)
    end
end

我已将 Pavans 代码添加到我的代码中,并且我还更改了底部的参数,现在这给了我未定义的方法 `create' for #。我认为这是进步?

【问题讨论】:

  • 其他人可以详细说明它可能是什么吗?因为我觉得除了第三次删除和重新安装之外,我已经用尽了所有途径,

标签: ruby-on-rails ruby routing paperclip strong-parameters


【解决方案1】:

不允许的参数:doc

您为 field doc 设置了 multiple :true,因此 doc 应该是一个数组 来接受这些值。您应该将doc_params 更改为以下

def doc_params
  params.require(:document).permit(:id, doc: [])
end

找不到处理程序 [#, @original_filename="P1150645.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"document[doc][]\"; filename=\"P1150645.jpg\"\r\nContent-Type: image/jpeg\r\n">]

您还应该将multipart: true 设置为表单以处理文件上传

<%= form_for @document, html: { multipart: true } do |f| %>

ActionController::RoutingError(没有路由匹配 [GET] "/docs/original/missing.png")

当一个对象没有上传的文件时,Paperclip 将尝试查找missing.png,并且您已经告诉 Paperclip 在哪里可以找到它!

class Document < ApplicationRecord
  has_attached_file :doc, :styles => { :medium => "250x250>", :thumb => "150x150>" }, :default_url => "/system/:attachment/:style/missing.jpg"
  do_not_validate_attachment_file_type :doc
end

更新:

您的create 操作应如下所示

def create
  @document = Document.new(doc_params)
  if @document.save
    params[:document][:doc].each do |d| #iterate over multiple attached files     
      @doumnet.create(doc: d)
    end
    flash[:success] = "The document was added!"
    redirect_to root_path
  else
    render 'new'
  end
end

【讨论】:

  • 之前试过,我得到 No handler found for [#<:http::uploadedfile:0x007feaf4b33cd8>, @original_filename="P1150645.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"document[doc][]\"; filename=\"P1150645.jpg\"\r\nContent-Type: image/jpeg\r\n">]
  • @Beamerr 更新了!
  • @Beamerr 进一步更新!
  • 我也在表单上尝试了 multipart: true 并且得到了相同的 No handler。我已经尝试了几乎所有关于堆栈溢出的建议。我可以设置默认网址,但那不是将照片上传到数据库?
  • @Beamerr 尝试将validates_attachment_content_type :doc, content_type: /\Aimage/ 添加到模型中
猜你喜欢
  • 2017-07-13
  • 2012-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-28
  • 1970-01-01
相关资源
最近更新 更多