Paperclip Giving Required field error - paperclip

in my project i have form in that there is file field to upload file and I am using paperclip gem for that and add only validation 'validates_attachment_content_type' but when i submit a form without any file selected it gives error of 'validates_attachment_content_type',
it should not give any error as i am not add validation 'validates_attachment_presence'. I am very confused for what it giving error of 'validates_attachment_content_type' when i submit a form without any file uploaded.

after googling for the same i got answer for this prob just we have to add :allow_nil => true in validation
for eg.
validates_attachment_content_type :logo, :content_type => ['image/jpeg','image/png','image /jpg','image/gif'],
:message=>"Image file must be of .jpeg,'.jpg', '.gif' or .png type",:allow_nil => true

:allow_nil => true
is realy work great and very easy to test.YOu can put it after your validation.

Related

Ruby open-uri open method loses file extension opening images

I'm using ruby 1.9.2 along with Rails 3.1.4 and Paperclip 2.4.5.
My issue is trying to save a paperclip attachment from a URI loses the file extension and saves the file without one resulting in issues with things like fancybox that require an extension.
Some example code:
uri = "http://featherfiles.aviary.com/2012-06-13/bbe5f0de1/0c5a672b88ea47ecb4631ac173e27430.png"
open(uri)
#=> #<File:/var/folders/zc/d69gxhzx10x_bvjrkqgyjgxr0000gn/T/open-uri20120613-27204-i6cldv>
Because there is no extension on the temp file paperclip is saving the file without one resulting in issues.
Has anyone run into this issue? I've seen multiple answers about using paperclip to store images from a URI but none seem to address the same problem we're running
Don't use the temporary file! It's there as a placeholder as the file is read from the port, and should be considered a private resource for OpenURI. Instead, use open(url).read and work with the resulting content by saving it.
Do something like:
require 'uri'
require 'open-uri'
url = 'http://www.iana.org/domains/example/index.html'
filename = File.basename(URI.parse(url).path)
File.open(filename, 'wb') do |fo|
fo.write(open(url).read)
end
Temporarily spooling to disk during an operation, especially a network operation, is common. Once the file's content has been accumulated, then it is available to be passed off to the app. read is blocking, so your code will stop there until the file is returned to you. Then you can play with it.
Extension isn't important for temporary file, but if you want use this file in code or save to another place. You can do it:
temp_file = open(params[:url])
def temp_file.original_filename; File.basename(base_uri.path); end
Now, you can save this temporary file to permanent space or use it in code; Original filename will be used automatically.
Im not sure if this will help in your case, but I was noticing similar issues in my project.
The issue turned out to be not caused by Paperclip nor open-uri, but the receiver of the paperclip file (in my case Spree Commerce). Check that you are assigning the paperclip object to the right object, and that it is being interpreted correctly.
The fix that worked for me was to change:
#product.images << Spree::Image.create({
:attachment => open(image_url)
}, :without_protection => true)
to
#product.master.images << Spree::Image.create({
:attachment => open(image_url)
}, :without_protection => true)
Good luck with your issue
Have you inclued the :extension in your path/url option?
For example:
has_attached_file :image,
...
:url => '/images/highlights/:id_partition/:style_:id.:extension',
:path => ':rails_root/files/images/highlights/:id_partition/:style_:id.:extension'
This will probably solve your problem.
You can force an extension there, but I don't think that's recommended.
Update – Paperclip can do this on its own!
Posted by Aditya Sanghi (thanks a lot!):
current_comments.pictures.create!(file: URI.parse(image_url))
Although keep in mind, that you still need to handle 500, 404, etc
errors (Paperclip can raise them).
Thanks to: https://mensfeld.pl/2013/12/rails-paperclip-open-uri-downloading-files-from-the-internet-and-saving-them-with-paperclip/
Yes, it is a problem but we can get around this with fancybox.
In the link tag(for image) add :type => 'image'
- #images.each do |image|
= link_to image_tag(image.attachment.url), image.attachment.url, class: "fancybox", type: 'image'
By specifying 'type', Fancybox overrides the type as image
https://groups.google.com/forum/?fromgroups=#!topic/fancybox/QgjquBCLynU

How to update address of a facebook page through API

I am trying to update address/location of a facebook business page through API using koala ruby gem, so far no working solution.
page_access_token = "gw4t3434"
page_api = Koala::Facebook::API.new(page_access_token)
page_api.graph_call('me', {:location => {:street => "my street"}}, 'post') #error. Koala::Facebook::APIError: OAuthException: (#100) Parameters do not match any fields that can be updated
page_api.graph_call('me', {:location => {:address => "my street"}}, 'post') #error. Koala::Facebook::APIError: OAuthException: (#100) Parameters do not match any fields that can be updated
page_api.graph_call('me', {:address => "my street"}}, 'post')# not raise error but not working
page_api.graph_call('me', {:street => "my street"}}, 'post')# not raise error but not working
I can not find clear explanation either in facebook api reference regarding updating address in a page. I may missing something...
You can't write to the location object, only read. See "Updating Page Attributes" in the API. Also, there is no permission to request for writing to a location object.
An alternative is that you write to the Page's about section - this is allowed. Perhaps you can place an address reference here to meet the requirement of making address changes visible to the end user.

How to make this code better? (sinatra + datamapper)

I'm new to this, and I'm using datamapper and sinatra to build a basic app. I have a settings page with a few text inputs for several different settings.
This page, when viewed, should pull the information from the database and populate the input boxes if they're there.
For my Setting class I have :name and :value
As of right now, I have the code working which allows a setting to be created if the name doesnt already exist, and it updates it otherwise.
Setting.first_or_create(:name => "seed").update(:name => "seed", :value => params[:seed])
3 problems:
if the input is blank (after the first time obviously), it overwrites it with ""
How can I shorten this code down? In a 'real' ruby program, should i define a method so theres not so much redundant code? I have 5 settings so i feel having that line of code 5 times with only a few things different is kind of poor. The difficulty is that I would be forced to name="" all my inputs the exact hash that i'm using. Im not sure if thats poor practice or not, or whether I should just do it all explicitly 5 times
In order to 'get' the data to display it i have this:
#seed = Setting.get(:name => "seed")
That obviously doesn't work... what I need is to get params[:value] WHERE :name => "seed" and the use <%= #seed(???) %> to print it out. im not sure how to do this
#seed = Setting.first_or_create(:name => "seed") # fetch and store
# update only if there was one
#seed.update(:name => "seed", :value => params[:seed]) if params[:seed].present?
<!-- show the value in the page -->
<%= #seed.value %>

Make user-inputted url into external link in rails

I want users to be able to enter a url and then put a link to that url in my view.
Valid inputs could be e.x. https://www.google.com/path, http://www.google.com, www.google.com
Is there are standard rails way to 1) validate that input is a valid url format and 2) convert that third format to http://www.google.com in my views so the external link works?
I don't want to re-invent the wheel if I can avoid it.
Check this out:
validates_format_of :website, :with => URI::regexp(%w(http https))
Source: http://intridea.com/2009/2/18/quick-tip-url-validation-in-rails?blog=company
To format a URL that is missing the protocol (http or https), I would do a before_save hook that prepends it if it's missing:
before_save :format_url
...
def format_url
self.website = "http://#{self.website}" unless self.website[/^https?/]
end
The Domainatrix gem comes highly recommended for validating URLs:
https://github.com/pauldix/domainatrix

Rails model validation not working

model:
validates :name, :presence => true
validates :year, :presence => true
validates :description, :presence => true
when submitting the form containing these fields, leaving the text boxes blank on purpose, instead of getting the Rails error messaging, I get the following exception thrown:
NoMethodError
You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.each
Any thoughts on why this may occur would be greatly appreciated.
A stab in the dark would be that its not your validations throwing the error message. My first instinct is that its the error view code (if you are looping through the errors the nil is possibly in there). Its also possible its an error in the controller but I would have to see the first couple lines of the backtrace to make a more informed guess.

Resources