paperclip + vestal_versions problem - ruby-on-rails

I need help to setup paperclip with vestal_versions. I followed this tutorial
http://blog.dmfranc.com/post/1036667709/paperclip-and-vestal-versions
But when i try to upload files, i get this error
[paperclip] Saving attachments.
Completed 500 Internal Server Error in 626ms
NoMethodError (undefined method `version' for #):
my file model are a belongs_to from the buildings and building has_menu building_pdf.
class BuildingPdf < ActiveRecord::Base
belongs_to :building
has_attached_file :pdf, :keep_old_files => true, :url => "/pdf/:id/versions/:version/:basename.:extension",
:path => ":rails_root/system/pdf/:id/:version/:basename.:extension"
Paperclip.interpolates :version do |attachment, style|
attachment.instance.version.to_s
end
end
here is my /lib/initializers/versioning_with_paperclip.rb
module Paperclip
class Attachment
def save
flush_deletes unless #options[:keep_old_files]
flush_writes
#dirty = false
true
end
end
end
what else i missing?
thanks.
PS. After i added versioning in my model i get this error
[paperclip] Saving attachments.
Completed 500 Internal Server Error in 1512ms
Mysql2::Error (Table 'db.versions' doesn't exist):
app/models/building_pdf.rb:10:in `version'
config/initializers/versioning_with_paperclip.rb:5:in `save'

You need to add (versioned) to your model
class BuildingPdf < ActiveRecord::Base
versioned
..
end

Related

Paperclip: Content Type Spoof trying to upload .gpx files

Apologies if this has been answered and I failed to find it. Any direction would be greatly appreciated.
Using Rails 4.1.4, Paperclip 4.2.0 and Simple Form 3.0.2.
After Submit, I get has an extension that does not match its contents output in the form error message.
In the server window:
Started POST "/routes" for 127.0.0.1 at 2014-08-28 15:18:25 +0700
Processing by RoutesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"5BCHGBkwQH4mlnTVjy/PpD53mJKJpSmBXwXT/oul7yY=", "route"=>{"track_attributes"=>{"gpx"=>#<ActionDispatch::Http::UploadedFile:0x007fa89c9cd348 #tempfile=#<Tempfile:/var/folders/_g/6shs5yrj36n960wpt880ysl80000gn/T/RackMultipart20140828-42106-vi71nb>, #original_filename="Serge's tracks.gpx", #content_type="application/octet-stream", #headers="Content-Disposition: form-data; name=\"route[track_attributes][gpx]\"; filename=\"Serge's tracks.gpx\"\r\nContent-Type: application/octet-stream\r\n">}, "title"=>"Serge track", "description"=>"loop of hang dong", "distance"=>"", "total_ascent"=>""}, "commit"=>"Create Route"}
Command :: file -b --mime '/var/folders/_g/6shs5yrj36n960wpt880ysl80000gn/T/f55fe48e09c9cc3ee6c6271fe94f407520140828-42106-1hgpby7.gpx'
[paperclip] Content Type Spoof: Filename Serge's_tracks.gpx ([]), content type discovered from file command: application/xml. See documentation to allow this combination.
(0.3ms) BEGIN
Command :: file -b --mime '/var/folders/_g/6shs5yrj36n960wpt880ysl80000gn/T/f55fe48e09c9cc3ee6c6271fe94f407520140828-42106-62bkvh.gpx'
[paperclip] Content Type Spoof: Filename Serge's_tracks.gpx ([]), content type discovered from file command: application/xml. See documentation to allow this combination.
(0.8ms) ROLLBACK
I haven't been able to find said documentation in the Paperclip docs.
Running file Serge\'s\ tracks.gpx --mime-type -b produces application/xml
My MVC looks like this:
class Track < ActiveRecord::Base
belongs_to :route
has_attached_file :gpx
validates_attachment_content_type :gpx, :content_type => /application\/xml/
end
class Route < ActiveRecord::Base
has_one :track, dependent: :destroy
accepts_nested_attributes_for :track
validates :title, presence: true
end
Inside RoutesController
def new
#route = Route.new
#route.track = Track.new
end
def create
#route = Route.new(route_params)
end
def route_params
params.require(:route).permit(:title, :description, :distance, :total_ascent, track_attributes: [:gpx])
end
The simple_form:
= simple_form_for #route do |r|
= r.simple_fields_for :track do |t|
= t.input :gpx
= r.input :title
= r.input :description
= r.input :distance
= r.input :total_ascent
= r.button :submit
As mentioned in this post: Paperclip gem spoofing error? and this article http://robots.thoughtbot.com/prevent-spoofing-with-paperclip, the problem was solved by apparently bypassing the command file -b --mime-type that is called by Paperclip.
To do this I created a paperclip.rb file in config/initializers.
Paperclip.options[:content_type_mappings] = {
:gpx => 'application/xml'
}
While the problem is solved, I am still confused as to why the problem existed when the file command was returning a correct result, and also curious where the #content_type="application/octet-stream" in the params is coming from.

Can't upload image using Paperclip 4.0 Rails 3

I've installed ImageMagick and I've installed the gem Paperclip (version 4.0). I've added:
Paperclip.options[:command_path] = 'C:\Program Files\ImageMagick-6.8.8-Q16'
to the development.rb
My photo.rb Model has this:
has_attached_file :image
validates_attachment_content_type :image, :content_type => ['image/jpeg', 'image/png', 'image/jpg']
I can choose a file in photos/new.html.erb but once I click on 'Create photo' button, the page reloads with a Paperclip specific error message saying:
1 error prohibited this photo from being saved:
Image translation missing:
en.activerecord.errors.models.photo.attributes.image.spoofed_media_type
Can someone help please?
Thanks
Add this to an initializer to disable spoofing protection:
require 'paperclip/media_type_spoof_detector'
module Paperclip
class MediaTypeSpoofDetector
def spoofed?
false
end
end
end
That message is raised by a validation check for content spoofing.
For Paperclip v.4 this generates a bug https://github.com/thoughtbot/paperclip/issues/1429
While for Paperclip v.3, it seems it just throws a deprecation warning, https://github.com/thoughtbot/paperclip/issues/1423
So I'd wait for Paperclip team to solve this bug before using version 4. At the moment I'd rather keep using version 3.
gem "paperclip", "~> 3.5.3"
This works on Paperclip v3.5.1 (hopefully will still work in V4):
has_attached_file :attachment,
styles: lambda { |a| a.instance.is_image? ? { *** image_styles ***} : { *** video_styles ***},
processors: lambda { |a| a.is_video? ? [ :ffmpeg ] : [ :thumbnail ] }
def is_video?
attachment.instance.attachment_content_type =~ %r(video)
end
def is_image?
attachment.instance.attachment_content_type =~ %r(image)
end

Ruby on Rails: paperclip error

I have a form that contains a file upload field named "application_path". I installed "Paperclip" GEM. But when i simply submit my form without selecting any file then i get error
undefined method `application_path_file_name' for #<ApplicationInstance:0x0000000561bc28>
Here are my request parameters shown in that error page
{"utf8"=>"✓",
"authenticity_token"=>"p3Y0SZT6wIonrrnzughybh8hywnkE1i3uBnxwrU4u9w=",
"application_instance"=>{"device_id"=>"",
"application_version_profile_id"=>""},
"commit"=>"Create Application instance"}
The above parameter does not contain "application_path" with blank value.
Here is my Model
class ApplicationInstance < ActiveRecord::Base
attr_accessible :application_version_profile_id, :device_id, :is_deleted, :application_path
# Validations
validates :application_version_profile_id, :presence => true
validates :device_id, :presence => true
validates_attachment_presence :application_path
validates_attachment_size :application_path, :less_than=>1.megabyte
What i am missing here?
You are missing the line that sets up paperclip for ApplicationInstance. in your application_instance.rb
has_attached_file :application_path, styles: { medium: '300x300>', thumb: '100x100>' }
You may also be missing the required columns for paperclip which you can generate by
rails g paperclip application_instance application_path
Following link may help you
Upload image using paperclip in Rails

How to create thumbnails only for image files with Paperclip?

I use the following code to create Assets from the uploaded files:
def upload
uploader = User.find_by_id(params[:uploader_id])
params[:assets].each do |file|
new_asset = uploader.assets.build(:asset => file) # Here the error appears
new_asset.save
end
...
end
I noticed that when I upload non-image files, e.g. my.xlsx, I got the following error:
[paperclip] identify -format %wx%h "C:/temp/stream20110628-460-3vqjnd.xlsx[0]" 2>NUL
[paperclip] An error was received while processing:
#<Paperclip::NotIdentifiedByImageMagickError: C:/temp/stream20110628-460-3vqjnd.xlsx is
not recognized by the 'identify' command.>
(For image files everything works fine: a thumbnail is created, and there is no error.)
Is that because Paperclip tries to create a thumbnail from my.xlsx ?
What configuration will create thumbnails only for image files ?
Here is some relevant code:
class Asset < ActiveRecord::Base
belongs_to :uploader, :class_name => "User"
has_attached_file :asset, :styles => { :thumb => "80x80#" }
end
I used the following nice solution:
before_post_process :image?
def image?
(asset_content_type =~ SUPPORTED_IMAGES_REGEX).present?
end
where:
SUPPORTED_IMAGE_FORMATS = ["image/jpeg", "image/png", "image/gif", "image/bmp"]
SUPPORTED_IMAGES_REGEX = Regexp.new('\A(' + SUPPORTED_IMAGE_FORMATS.join('|') + ')\Z')
Change the has_attached_file line to read:
has_attached_file :asset, :styles => { :thumb=> "80x80#" }, :whiny_thumbnails => false
This will prevent it from raising an error when thumbnails are not created. Note though that it won't raise errors if one occurs when processing an image though.

multiple paperclip attachements with watermark processor

I'm having a ton of trouble with uploading multiple attachments with paperclip and processing them with a watermark.
I have 2 models, Ad and Photo.
The Ad has_many :photos and the Photo belongs_to :ad.
To be more exact in /models/ad.rb I have:
class Ad < ActiveRecord::Base
has_many :photos, :dependent => :destroy
accepts_nested_attributes_for :photos, :allow_destroy => true
end
and my photo.rb file looks like this:
class Photo < ActiveRecord::Base
belongs_to :ad
has_attached_file :data,
:styles => {
:thumb => "100x100#",
:first => {
:processors => [:watermark],
:geometry => '300x250#',
:watermark_path => ':rails_root/public/images/watermark.png',
:position => 'SouthEast' },
:large => {
:processors => [:watermark],
:geometry => '640x480#',
:watermark_path => ':rails_root/public/images/watermark.png',
:position => 'SouthEast' }
}
end
In my view I use this to add the file fields
<% f.fields_for :photos do |p| %>
<%= p.label :data, 'Poza:' %> <%= p.file_field :data %>
<% end %>
In my controller, in the edit action i use 4.times {#ad.photos.build} to generate the file fields.
It all works fine and dandy if I don't use the watermark processor, if I use a normal has_attached_file declaration, like this:
has_attached_file :data,
:styles => {
:thumb => "100x100#",
:first => '300x250#',
:large => '640x480#'
}
But when I use the watermark processor I always get this error:
NoMethodError in PublicController#update_ad
You have a nil object when you didn't expect it!
You might have expected an instance of ActiveRecord::Base.
The error occurred while evaluating nil.[]
..............................
/usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/nested_attributes.rb:350:in `assign_nested_attributes_for_collection_association'
/usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/nested_attributes.rb:345:in `each'
/usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/nested_attributes.rb:345:in `assign_nested_attributes_for_collection_association'
/usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/nested_attributes.rb:243:in `photos_attributes='
/usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/base.rb:2746:in `send'
/usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/base.rb:2746:in `attributes='
/usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/base.rb:2742:in `each'
/usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/base.rb:2742:in `attributes='
/usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/base.rb:2628:in `update_attributes'
/home/alexg/Sites/vandmasina/app/controllers/public_controller.rb:217
/home/alexg/Sites/vandmasina/app/controllers/public_controller.rb:216:in `update_ad'
The parameters are ok, as far as I can say
Parameters:
{"commit"=>"Salveaza modificarile",
"ad"=>{"price"=>"6000",
"oras"=>"9",
"photos_attributes"=>{"0"=>{"data"=>#<File:/tmp/RackMultipart20100928-5130-b42noe-0>},
"1"=>{"data"=>#<File:/tmp/RackMultipart20100928-5130-r0ukcr-0>},
"2"=>{"data"=>#<File:/tmp/RackMultipart20100928-5130-mb23ei-0>},
"3"=>{"data"=>#<File:/tmp/RackMultipart20100928-5130-1bpkm3b-0>}},
The Watermark processor /lib/paperclip_processors/watermark.rb looks like this:
module Paperclip
class Watermark < Processor
class InstanceNotGiven < ArgumentError;
end
def initialize(file, options = {},attachment = nil)
super
#file = file
#current_format = File.extname(#file.path)
#basename = File.basename(#file.path, #current_format)
#watermark = ':rails_root/public/images/watermark.png'
#current_geometry = Geometry.from_file file # This is pretty slow
#watermark_geometry = watermark_dimensions
end
def watermark_dimensions
return #watermark_dimensions if #watermark_dimensions
#watermark_dimensions = Geometry.from_file #watermark
end
def make
dst = Tempfile.new([#basename, #format].compact.join("."))
watermark = " \\( #{#watermark} -extract #{#current_geometry.width.to_i}x#{#current_geometry.height.to_i}+#{#watermark_geometry.height.to_i /
2}+#{#watermark_geometry.width.to_i / 2} \\) "
command = "-gravity center " + watermark + File.expand_path(#file.path) + " " +File.expand_path(dst.path)
begin
success = Paperclip.run("composite", command.gsub(/\s+/, " "))
rescue PaperclipCommandLineError
raise PaperclipError, "There was an error processing the watermark for #{#basename}" if #whiny_thumbnails
end
dst
end
end
end
I have tried the processor in a normal app, without multiple attachments and it works perfect. It doesn't work with nested_attributes as far as I can tell.
The app is rails 2.3.5 with ruby 1.8.7 and paperclip 2.3.11
If you can provide any help it would be appreciated a lot, since I've been trying to figure this out for 2 days now :)
If you use rails 3 and paperclip > 2.3.3, try https://gist.github.com/843418 source.
Oh, man, that was a tough one!
You have few errors in your code and none is related to nested models. My explanation is for Rails 3 & Paperclip 2.3.3
a) the :rails_root thing doesn't work. This interpolation is used only in url/path and not on custom options. So you should replace it with Rails.root.join("public/images...")
b) you simply ignore the :watermark_path option and you use only hardcoded path (in initialization method). So it doesn't matter what you have in your :styles as it always go for .../images/watermark.png. The :rails_root thingy there again so it cannot work.
c) when you pass a parameter to Paperclip.run("composite", "foo bar there") it actually executes this command:
composite 'foo bar there'
can you see the single quotes? Because of that the composite command see your parameters as one huge parameter and doesn't understand it at all. If you pass it as an array, then every item is enclosed in the quotes, not the array as a whole.
So here is the improved version of watermark processor:
module Paperclip
class Watermark < Processor
class InstanceNotGiven < ArgumentError;
end
def initialize(file, options = {},attachment = nil)
super
#file = file
#current_format = File.extname(#file.path)
#basename = File.basename(#file.path, #current_format)
# PAWIEN: use default value only if option is not specified
#watermark = options[:watermark_path] || Rails.root.join('public/images/watermark.png')
#current_geometry = Geometry.from_file file # This is pretty slow
#watermark_geometry = watermark_dimensions
end
def watermark_dimensions
return #watermark_dimensions if #watermark_dimensions
#watermark_dimensions = Geometry.from_file #watermark
end
def make
dst = Tempfile.new([#basename, #format].compact.join("."))
dst.binmode
begin
# PAWIEN: change original "stringy" approach to arrayish approach
# inspired by the thumbnail processor
options = [
"-gravity",
"center",
"#{#watermark}",
"-extract",
"#{#current_geometry.width.to_i}x#{#current_geometry.height.to_i}+#{#watermark_geometry.height.to_i / 2}+#{#watermark_geometry.width.to_i / 2}",
File.expand_path(#file.path),
File.expand_path(dst.path)
].flatten.compact.join(" ").strip.squeeze(" ")
success = Paperclip.run("composite", options)
rescue PaperclipCommandLineError
raise PaperclipError, "There was an error processing the watermark for #{#basename}" if #whiny_thumbnails
end
dst
end
end
end
Hope that helped you!
UPDATE: You need to use latest paperclip gem from github
gem 'paperclip', '>= 2.3.3', :git => "http://github.com/thoughtbot/paperclip.git"
In this version the formats of #run were changed once again so I've updated the code. It really should work as I've created test application and it's doing what supposed.
UPDATE 2: Repo with working example:
git://repo.or.cz/paperclip-mass-example.git
Just from a quick glance it looks like watermark_path should be "#{Rails.root}/..." though it looks like you have a lot going on here.
Also, I don't see your form as in form_for. Make sure you have {:multipart => true}

Resources