简体   繁体   English

使用JSON时如何传递参数?

[英]How to pass parameters when using JSON?

I can't get my images to save because of an Unpermitted parameter: image error . 由于Unpermitted parameter: image error不允许,我无法保存Unpermitted parameter: image error Using dropzone.js , I have to upload the form by JSON if I want to have to ability to drag and drop images on the file field. 使用dropzone.js ,如果我想能够将图像拖放到文件字段中,则必须通过JSON上传表单。 I'm trying to allow only one image to be uploaded to the model. 我试图只允许将一张图片上传到模型。 Here is my code: 这是我的代码:

items.rb items.rb

class Item < ActiveRecord::Base
.....
validates_inclusion_of :found, in: [true, false]

has_attached_file :image, :styles => { :medium => "350x350>", :thumb => "100x100>" }
validates_attachment :image,
        content_type: { content_type: [ "image/jpg", "image/jpeg", "image/png" ] },
        size: { in: 0..1.megabytes },
        matches: [/png\Z/, /jpe?g\Z/]

end

items.coffee items.coffee

  $('#new_item').dropzone
    acceptedFiles: '.jpeg, .jpg, .png'
    maxFilesize: 1
    maxFiles: 100
    addRemoveLinks: true
    paramName: 'item[image]'
    clickable: '#image-preview'
    headers: "X-CSRF-Token" : $('meta[name="csrf-token"]').attr('content')
    previewsContainer: '#image-preview'
    thumbnailWidth: 300
    thumbnailHeight: 300
    autoProcessQueue: false
    uploadMultiple: true
    parallelUploads: 100
    init: ->
      myDropzone = this
      @element.querySelector('#item-submit').addEventListener 'click', (e) ->
        e.preventDefault()
        e.stopPropagation()
        if myDropzone.getQueuedFiles().length > 0
          myDropzone.processQueue()
        else
          $("#new_item").submit();
        return
      @on 'sendingmultiple', ->
        return
      @on 'successmultiple', (files, response) ->
        return
      @on 'errormultiple', (files, response) ->
        return
      return

items_controller.rb items_controller.rb

class ItemsController < ApplicationController

      def create
        @item = current_user.items.build(item_params)
        if @item.save
          if request.xhr?
            render json: {
              location: url_for(controller: 'items', action: 'continue', id: @item),
              flash: {notice: "Successfully posted item!"}
            }
          else
            redirect_to(controller: 'items', action: 'continue', id: @item)
          end
        else
          render json: @item.errors, status: :unprocessable_entity
        end
      end

  private

  def item_params
    params.require(:item).permit(:name, :description, :image)
  end

  def find_item
    @item = Item.find(params[:id])
  end

end

routes.rb 的routes.rb

  resources :items do
    collection do
      get 'lost', to: 'items#index_lost'
      get 'found', to: 'items#index_found'
    end
    get '/post/continue', to: 'items#continue', on: :member
  end

items/_form.haml 项目/ _form.haml

= form_for @item, validate: true, html: {multipart: true} do |f|
    = f.label :name, class: 'col-lg-2 control-label'
        = f.text_field :name
    %main#image-preview
        .fallback
            = f.file_field :image, multiple: false
    .submit-section
        .col-lg-12.col-md-12
            = f.submit 'Done', id: 'item-submit'

(Note: validate: true is from the client_side_validation gem ) (注意: validate: true来自client_side_validation gem

So the error I get after submitting the form is: 所以提交表单后出现的错误是:

Started POST "/items" for 127.0.0.1 at ............
Processing by ItemsController#create as JSON
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"SAIGiG9SjnuTKfsmxszBFfK+lZVojS2UmDi9hTeC8wI6B2fGZ+sZM9te3lIFkFsT30SdFWjyXZMZI7zXAlAMGA==", "item"=>{name"=>"Post Item", image"=>{"0"=>#<ActionDispatch::Http::UploadedFile:0x007f3d248b5a98 @tempfile=#<Tempfile:/tmp/RackMultipart20151002-2427-1cvzgsi.jpg>, @original_filename="haribo.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"item[image][0]\"; filename=\"haribo.jpg\"\r\nContent-Type: image/jpeg\r\n">}}, "null"=>"", "commit"=>"Done"}
Unpermitted parameter: image
..........
    Completed 200 OK in 230ms (Views: 0.3ms | Searchkick: 31.1ms | ActiveRecord: 14.3ms)

Now after all of this it still saves but it just causes image not to because I also want to allow the user to submit the form without an image. 现在,尽管如此,它仍然可以保存,但只会导致图像不显示,因为我也希望允许用户提交没有图像的表单。 How do I fix this? 我该如何解决?

You submitted params include image attribute as Hash 您提交的参数包括图像属性作为哈希

image"=>{"0"=>#<ActionDispatch::Http::UploadedFile:0x007f3d248b5a98 ...

It should be like : 它应该像:

"image"=>#<ActionDispatch::Http::UploadedFile:0x007f3d248b5a98 @tempfile= ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM