Colorswave не может рассеивать защищенные атрибуты озадача: путь при загрузке с помощью jQuery-fileupload-Rails

StackOverflow https://stackoverflow.com//questions/11690240

Вопрос

Я пытаюсь получить простую загруженную загрузку файлов, используя

    .
  • jquery-fileupload-rails
  • Carrierwave
  • туман

Я не могу найти причину следующей ошибки

Started POST "/pictures" for 127.0.0.1 at 2012-07-27 15:19:37 +0100
Processing by PicturesController#create as JSON
  Parameters: {"utf8"=>"✓",
  authenticity_token"=>"NKek0e/kfVRUk4SVBjokO5rL446dKvHo9+7mKuH0HKs=", "picture"=>   
  {"path"=>#  <ActionDispatch::Http::UploadedFile:0x00000002d48fa8 
  @original_filename="IMG_0001.JPG", @content_type="image/jpeg", @headers="Content-
  Disposition: form-data; name=\"picture[path]\"; filename=\"IMG_0001.JPG\"\r\nContent-
  Type: image/jpeg\r\n", @tempfile=#<File:/tmp/RackMultipart20120727-7807-1bcbfof>>}}
Completed 500 Internal Server Error in 1ms

ActiveModel::MassAssignmentSecurity::Error (Can't mass-assign protected attributes: 
path):
  app/controllers/pictures_controller.rb:9:in `new'
  app/controllers/pictures_controller.rb:9:in `create'
.

Модель, контроллер и вид взяты из

https://github.com/blueim/jquery-file-upload / wiki / rails-setup-for-v6

Сообщение об ошибке приводит меня к тому, что мне нужно сделать «путь», а как?Обратите внимание, что бит загрузки jQuery-файлов работает (у меня есть кнопки Bootstrap, картинки появляются на экране и т. Д., Только файл загружается, очевидно, не работает!)

Для полноты, это picture.rb:

class Picture < ActiveRecord::Base

  include Rails.application.routes.url_helpers
  attr_accessible :avatar
  mount_uploader :avatar, AvatarUploader

  def to_jq_upload
    {
      "name" => read_attribute(:avatar),
      "size" => avatar.size,
      "url" => avatar.url,
      "thumbnail_url" => avatar.thumb.url,
      "delete_url" => picture_path(:id => id),
      "delete_type" => "DELETE" 
    }
  end
end
.

Соответствующий контроллер составляет

class PicturesController < ApplicationController  

  def index
    @pictures = Picture.all
    render :json => @pictures.collect { |p| p.to_jq_upload }.to_json
  end

  def create
    @picture = Picture.new(params[:picture])
    @picture.save!
    if @picture.save
      respond_to do |format|
        format.html {  
          render :json => [@picture.to_jq_upload].to_json, 
          :content_type => 'text/html',
          :layout => false
        }
        format.json {  
          render :json => [@picture.to_jq_upload].to_json     
        }
      end
    else 
      render :json => [{:error => "custom_failure"}], :status => 304
    end
  end

  def destroy
    @picture = Picture.find(params[:id])
    @picture.destroy
    render :json => true
  end

end
.

Это класс загрузки:

class AvatarUploader < CarrierWave::Uploader::Base

  storage :file

  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end


end
.

Это было полезно?

Решение 2

Я выяснил решение сам: ошибка была в представлении, где вместо: Путь следует читать: аватар, а: аватар должен быть доступным.Пример реализации, в которых находятся параметры загрузки файлов jQuery, можно найти на https://github.com/apotry/jquery_fileupload_carrierwave_fog

Другие советы

Эта ошибка вызвана загрузкой, который устанавливается неправильно. Есть опечатка, может быть в:

mount_uploader :avater, AvatarUploader
.

Это должно быть

mount_uploader :avatar, AvatarUploader
.

Попробуйте, что

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top