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
Related
I am working on an ecommerce website using Solidus, Rails. The site allows you to order photo frames & prints from a variety of options.
To print a photo a user must upload the jpg file of the photo. So, to allow that I modified the orders table and added a paperclip attachment called 'attachment'
I ran the following command
rails generate paperclip SpreeOrder attachment
Which generated the migrations, then I ran rake db:migrate
Then I created a spree/order_decorator.rb file, and added has_attached_file
module Spree::OrderDecorator
has_attached_file :attachment, styles: {
:medium => {
:geometry => "640x480",
:format => 'jpeg'
},
:thumb => { :geometry => "160x120", :format => 'jpeg', :time => 10}
}, :processors => [:transcoder]
validates_attachment_content_type :attachment, content_type: /\Aimage\/.*\z/
Spree::Order.prepend self
end
After this I ran the server, and ended up getting this error
undefined method `has_attached_file' for Spree::OrderDecorator:Module (NoMethodError)
I have configured solidus for use with paperclip only, so I am really confused as to why I am getting this error, even later I manually went and generated a paperclip.rb file in the config/initializers directory, but still I get the same error.
Please help with this!!
Thank You!!
You should add those paperclip method at class level in the prepended module:
def self.prepended(base)
base.has_attached_file
end
I am new to paperclip, and I wanted to see how it would work. I generated a simple model Monkey and got the following:
rails g scaffold monkey description age:datetime
rails g paperclip monkey facepic
rake db:migrate
Model
class Monkey< ActiveRecord::Base
has_attached_file :facepic, :styles => { :medium => "300x300>", :thumb => "100x100>" }
end
View new/edit
<%= form_for #monkey, :url => monkies_path, :html => { :multipart => true } do |f| %>
...
<div class="field">
<%= f.label :facepic %><br>
<%= f.file_field :facepic %>
</div>
View show
<%= image_tag #monkey.facepic.url %>
Controller
#monkey = Monkey.new(monkey_params)
I can create new monkeys, but the show view doesn't seem to find the uploaded file. I have no error messages, except a routing error to 'missing.png'. There is no trace to the uploaded image. I am using Rails 4.1.6. What am I missing here? How do I troubleshoot this thing? The gem is installed and also imagemagick is installed.
This is what the logs say:
ActionController::RoutingError (No route matches [GET] "/facepics/original/missing.png"):
...
Started GET "/monkies/new" for 127.0.0.1 at 2014-09-19 14:40:22 +0200
Processing by MonkiesController#new as HTML
Rendered monkies/_form.html.erb (4.0ms)
Rendered monkies/new.html.erb within layouts/application (5.0ms)
Completed 500 Internal Server Error in 12ms
ActionView::Template::Error (No route matches {:action=>"show", :controller=>"monkies"} missing required keys: [:id]):
There is no error message displayed however when I create a new monkey... :'(
EDIT:
The Monkey model is created, but the paperclip columns remain empty.
This error clearly show that your images are not getting saved because path and url not specified in your has_attached_file block. It should be like :
has_attached_file :facepic,
:path => ":rails_root/public/system/:attachment/:id/:style/:filename",
:url => "/system/:attachment/:id/:style/:filename",
:styles => { :medium => "300x300>", :thumb => "100x100>" },
:default_url => "path to default image"
here default_url show image that you want if no image uploaded. For more detail you can go here http://rdoc.info/gems/paperclip/4.2.0/Paperclip/ClassMethods%3ahas_attached_file .
And for other error you can follow this link Paperclip::Errors::MissingRequiredValidatorError with Rails 4
Starting with Paperclip version 4.0, all attachments are required to include a content_type validation, a file_name validation, or to explicitly state that they're not going to have either.
Paperclip raises Paperclip::Errors::MissingRequiredValidatorError error if you do not do any of this.
In your case, you can add any of the following line to your Post model, after specifying has_attached_file :image
Option 1: Validate content type
validates_attachment_content_type :image, :content_type => ["image/jpg", "image/jpeg", "image/png", "image/gif"]
-OR- another way
validates_attachment :image, content_type: { content_type: ["image/jpg", "image/jpeg", "image/png", "image/gif"] }
-OR- yet another way
is to use regex for validating content type.
Option 2: Validate filename
validates_attachment_file_name :avatar, :matches => [/png\Z/, /jpe?g\Z/, /gif\Z/]
Option 3: Do not validate
If for some crazy reason (can be valid but I cannot think of one right now), you do not wish to add any content_type validation and allow people to spoof Content-Types and receive data you weren't expecting onto your server then add the following:
do_not_validate_attachment_file_type :image
Note:
Specify the MIME types as per your requirement within content_type/ matches options above. I have just given a few image MIME types for you to start with.
Reference:
Refer to Paperclip: Security Validations, if you still need to verify. :)
For details you can go to This question
I am sorry to say that my problem eventually was a bunch of things:
Had to add :facepic to the strong params
Had to add validations of content type to the model
Paperclip has a dependency... the file-command, which isn't shipped on Windows.
which can be downloaded here: http://sourceforge.net/projects/gnuwin32/?source=typ_redirect
After all three, it works like a charm!
Thank you all!
I'm using Rails 4.0.0 with Paperclip 4.1.1 for attaching mp3 and pdf files. I'm writing my integration tests in Rspec with Capybara.
I have content type and file name validations in place for both types of files.
class Song < ActiveRecord::Base
validates :title, presence: true
validates :writeup, presence: true
has_attached_file :mp3
validates_attachment :mp3,
:content_type => { :content_type => "audio/mp3" },
:file_name => { :matches => [/mp3\Z/] }
has_attached_file :chords
validates_attachment :chords,
:content_type => { :content_type => 'application/pdf' },
:file_name => { :matches => [/pdf\Z/] }
end
I use this in my integration test to fill in attributes for a valid song:
def fill_in_valid_song
fill_in("Title", with: "Valid Song")
fill_in("Writeup", with: "Description of song")
attach_file("Mp3", File.join(Rails.root, "/spec/factories/Amazing_Grace.mp3" ))
attach_file("Chords", File.join(Rails.root, "/spec/factories/FakeChordChart.pdf" ))
end
When I run the integration test for creating a valid song, the pdf file is accepted, but the mp3 file fails the content type validation.
When I follow the same steps myself in the browser, the song uploads successfully without errors. The model spec also passes using the same file.
I thought the problem might be the capital "M" in "Mp3" when I attach the file, but this is just to specify which file field the attachment goes with. When I tried changing it to a lowercase "m", the error changed to Capybara not being able to find the field.
Change the content type validation for the mp3 file to be:
validates_attachment :mp3,
:content_type => { :content_type => ["audio/mpeg", "audio/mp3"] },
:file_name => { :matches => [/mp3\Z/] }
The RFC defined MIME type for mp3 files is audio/mpeg. However some browsers load them as audio/mp3 which is probably why it works through the browser.
If this doesn't work you could also add audio/mpeg3 and audio/x-mpeg-3 as I've seen these used too.
We have code that looks like run of the mill paper clip:
has_merchants_attached_file :pdf,
storage: :s3,
s3_credentials: Mbc::DataStore.s3_credentials,
s3_permissions: :private,
path: ":identifier_template.pdf",
bucket: Mbc::DataStore.forms_and_templates_bucket_name
validates_attachment_file_name :pdf, :matches => [/pdf\Z/]
Which generates an error:
undefined method `validates_attachment_file_name' for #<Class:0x007fba67d25fe0>
Interestingly enough, when we down grade back to 3.5, we encounter the same issue.
The controller that is generating this is:
def index
#fidelity_templates = FidelityTemplate.order("identifier asc").all
end
Additionally:
def has_merchants_attached_file(attribute, options={})
if Rails.env.test? || Rails.env.development?
has_attached_file attribute,
path: "paperclip_attachments/#{options[:path]}"
else
has_attached_file attribute, options
end
end
Any thoughts on what could be causing this?
You can read about the provided validators here:
https://github.com/thoughtbot/paperclip#validations
The included validators are:
AttachmentContentTypeValidator
AttachmentPresenceValidator
AttachmentSizeValidator
They can be used in either of these ways:
# New style:
validates_with AttachmentPresenceValidator, :attributes => :avatar
# Old style:
validates_attachment_presence :avatar
UPDATE ...
If you read further down the link I've given above you'll get to a section on Security Validations (Thanks Kirti Thorat):
https://github.com/thoughtbot/paperclip#security-validations
They give an example on how to validate the filename format:
# Validate filename
validates_attachment_file_name :avatar, :matches => [/png\Z/, /jpe?g\Z/]
From your code snippet it looks like your validation should work as-is.
However, I've never seen paperclip used with this syntax:
has_merchants_attached_file ...
Perhaps that's the source of your issues? You would usually use the following to attach files to your model:
has_attached_file :pdf ...
I am using rails 3.1.
I am trying to upload .docx file without proper file name (it contains only extension 'docx'), while saving it should validate like "file name is invalid".
In model,
validates_attachment_presence :document
validates_attachment_size :document, :less_than => 5.megabytes, :message => "should be less than 5Mb"
validates_attachment_content_type :document, :content_type => ['application/txt', 'text/plain',
'application/pdf', 'application/msword',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/vnd.oasis.opendocument.text',
'application/x-vnd.oasis.opendocument.text',
'application/rtf', 'application/x-rtf', 'text/rtf', 'text/richtext', 'application/doc', 'application/x-soffice', 'application/octet-stream']
Paperclip gem which i am using,
paperclip (3.0.4, 2.8.0, 2.4.5)
Eg : I am trying to upload ' .docx' file.
Please suggest how to avoid saving these kind of files.