如何在使用JSON时传递参数?

时间:2015-10-03 03:34:18

标签: ruby-on-rails json ruby-on-rails-4 paperclip

由于Unpermitted parameter: image error,我无法保存我的图片。使用dropzone.js,如果我想要在文件字段上拖放图像,我必须通过JSON上传表单。我试图只允许将一个图像上传到模型中。这是我的代码:

  

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

  $('#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

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

  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
  

项/ _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'

(注意:validate: true来自client_side_validation gem

所以提交表单后我得到的错误是:

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)

现在所有这一切仍然保存,但它只是导致图像不能,因为我也想让用户提交没有图像的表单。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

您提交的params包含图像属性为Hash

Integer minimum = null;
Integer maximum = null;

for (int i = 0; i < 5; i++) {
  int number = kb.nextInt();
  if (minimum == null || number < minimum) {
    minimum = number;
  }
  if (maximum == null || number > maximum) {
    maximum = number;
  }
}

System.out.println("minimum: " + minimum);
System.out.println("maximum: " + maximum);

应该是这样的:

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