Issue updating file attachment(image) using Attachment_fu - ruby-on-rails-3

I am able to upload image files as attachments using Attachment_fu but when I try to edit/ modify images which were already uploaded, it does not work.
In my Controller I have this:
def update
#sponsor_account = SponsorAccount.find( params[:id] )
if params[:showcase_category_image_file] &&
!params[:showcase_category_image_file].blank?
#sponsor_account.showcase_category_image =
ShowcaseCategoryImage.new(:uploaded_data =>
params[:showcase_category_image_file])
***This logs - Now the file name is: ***
Rails.logger.info("Now the file name is: #
{#sponsor_account.showcase_category_image.filename}")
end
#sponsor_account.update_attributes( params[:sponsor_account] )
if #sponsor_account.save
flash[:notice] = "Showcase category #{#sponsor_account.name} was updated!"
else
flash[:errors] = #sponsor_account.errors
end
redirect_to sponsor_accounts_path
end
ShowcaseCategoryImage is defined as follows:
has_attachment :content_type => :image,
:storage => :file_system,
:max_size => 5.megabytes,
:thumbnails => { :large => [350, 100], :medium => [200, 90], :thumb =>
[35,35], :preview => [60,60] }
validates_as_attachment
The view has a file_field_tag as follows:
<%= file_field_tag :showcase_category_image_file%>
and my SponsorAccount model says:
has_one :showcase_category_image, :as => :owner, :dependent => :destroy
validates_presence_of :showcase_category_image, :on => :create
Almost similar code works perfectly ok in 'create' but here in 'update' action where there is already a value, this code is not working.
I am getting the below error msgs:
Completed 500 Internal Server Error in 1089ms
ActionView::Template::Error (undefined method `public_filename' for nil:NilClass):
Obviously this error is in the index action where it tries to list all records and their attachments. Since this attachment is empty after the update, this error is thrown in the redirect_to part.
I am using REE1.8.7 and rails 3.2.9
Please help!

This issue was solved when I added :multipart => true in the 'View'. I am using rails 3.2.9 and the rails api has this to say about the 'file_field_tag':
file_field_tag(name, options = {}) Link
Creates a file upload field. If you are using file uploads then you will also need to set the multipart option for the form tag:

Related

render partial from controller with :layout => !request.xhr? returns missing template?

I cloned and tweak this rails app and I am experiencing some trouble with rendering a partial when on ajax request, in the logs I see that the guilty line is in the registrations_controller.rb (Devise)
class RegistrationsController < Devise::RegistrationsController
def create
build_resource
if resource.save
if resource.active_for_authentication?
sign_in(resource_name, resource)
(render(:partial => 'thankyou', :layout => false) && return) if request.xhr?
respond_with resource, :location => after_sign_up_path_for(resource)
else
resource.update_attribute(:encrypted_password, nil) # make sure there is no password
expire_session_data_after_sign_in!
(render(:partial => 'thankyou', :layout => false) && return) if request.xhr?
respond_with resource, :location => after_inactive_sign_up_path_for(resource)
end
else
clean_up_passwords resource
render :partial => 'email_capture', :action => :new, :layout => !request.xhr?**
end
end
protected
def after_inactive_sign_up_path_for(resource)
'/thankyou.html'
end
def after_sign_up_path_for(resource)
redirect_to root_path
end
end
The error message returned is this:
ActionView::MissingTemplate - Missing partial
with {:locale=>[:en], :formats=>[:html], :handlers=>[:erb, :builder,
:coffee, :haml]}. Searched in: *
"/Users/Davide/Documents/Jobsite/rails-prelaunch-signup-1click/app/views"
* "/Users/Davide/.rbenv/versions/1.9.3-p194/lib/ruby/gems/1.9.1/gems/devise_invitable-1.1.8/app/views"
* "/Users/Davide/.rbenv/versions/1.9.3-p194/lib/ruby/gems/1.9.1/gems/devise-2.2.4/app/views"
Interestingly if I remove the :layout => !=request.xhr? parameter the partial gets found but the page refreshes and the loses all the stylesheets and other assets.
Any idea where should I start looking?
Thanks!
I have also cloned and modified that project, and ran into nearly the same issue. For me, the problem would appear after the second failure of saving a bad email address--but the result was identical.
By using context and information from the following question/answer:
form returned from AJAX request is not recognized as 'remote' when submitted
I was able to make a change that resolved my issue. In _email_capture.html.erb, add :remote => true, to the simple_form_for line. In my case, the whole revised line is:
<%= simple_form_for resource, :as => resource_name, :remote => true, :url => registration_path(resource_name) , :html => {:class => 'form-inline'} do |f| %>
Hope this helps you, too!

Rails 3.0 associated model with download 'save to' image

My Rails 3.0.3 application has a scaffold 'month' which has a link where the user can download an image using 'save to'.
Now I need to make an association where the month model belongs_to the wallpaper model.
Routes:
root :to => 'inicio#index'
resources :wallpapers do
resources :months
end
# the route that works with no association
# match 'download/:id' => 'months#download', :as => :download
# the route I tried
match 'wallpapers/:id/months/:id' => 'months#download', :as => :download
Month model:
class Month < ActiveRecord::Base
belongs_to :wallpaper
has_attached_file :wallpaper_picture, :styles => {
:default => { :geometry => '530x330', :quality => 80, :format => 'jpg'}
}
end
Wallpaper model with friendlyid:
class Wallpaper < ActiveRecord::Base
has_many :months, :dependent => :destroy
extend FriendlyId
friendly_id :title, :use => :slugged
end
In months_controller I made the download method, this method works with no association:
class MonthsController < InheritedResources::Base
belongs_to :wallpaper, :finder => :find_by_slug!
def download
#wallpaper = Wallpaper.find(params[:wallpaper_id])
#month = #wallpaper.month.find(params[:id])
send_file #month.wallpaper_picture.path,
:filename => #month.wallpaper_picture_file_name,
:type => #month.wallpaper_picture_content_type,
:disposition => 'attachment'
end
end
View months/index
- #months.each do |month|
= link_to image_tag(month.wallpaper_picture(:default)), wallpaper_month_path(month.wallpaper, month)
I've tried changing in the months_controller the download method, but it is wrong:
#months = Wallpaper.month.conditions({:person_id => some_id})
Here is how I got it
Routes
resources :wallpapers do
resources :months
end
match 'wallpaper/:wallpaper_id/download/:id' => 'months#download', :as => :download
In the routes I must pass the :wallpaper_id (has_many :months),
the :id is the id of the current controller (belongs_to :wallpaper)
'download' will be the name of the path used in the view 'download_path'
In this path I must pass the foreign key and the id
View months/index
- #months.each do |month|
= link_to 'Download Picture', download_path(month.wallpaper_id, month.id)
In months_controller the download method will receive those parameters and pass the associated image to the send_file method.
def download
#wallpaper = Wallpaper.find(params[:wallpaper_id])
#month = #wallpaper.months.find(params[:id])
send_file #month.wallpaper_picture.path,
:filename => #month.wallpaper_picture_file_name,
:type => #month.wallpaper_picture_content_type,
:disposition => 'attachment'
end
PD: if send_file fails in Production, change it to send_data or
comment out this line in config/production.rb
config.action_dispatch.x_sendfile_header = "X-Sendfile"
send_file just sends an empty file

inconsistant photo url using paperclip when query in two apps

I am using paperclip to upload photos in my two rails app which share a single database. Now the problem is, if I upload a photo in app-a, for instance, paperclip gives me a url as:
http://s3.amazonaws.com/testing-item-photos-akiajbfjoiwfjzd6aypa/Users/yujunwu/app-a/public/item_19/created_at_2012-09-29%2021:52:02%20UTC/large.jpg?1348955522
Here is what I set up in my item model:
class Item < ActiveRecord::Base
attr_accessible :photo, :photo_url, :poll_id, :brand, :number_of_votes
has_attached_file :photo,
:styles => { :thumbnail => "100x100#",
:small => "150x150>",
:medium => "250x250>",
:large => "400x400>" },
:storage => :s3,
:s3_credentials => S3_CREDENTIALS,
:url=>"/item_:id/created_at_:created_at/:style.jpg"
Paperclip.interpolates :created_at do |attachment, style|
attachment.instance.created_at
end
end
In the other app app-b, when I query the url with item.photo.url(:large), it gave me:
http://s3.amazonaws.com/testing-item-photos-akiajbfjoiwfjzd6aypa/Users/yujunwu/app-b/public/item_19/created_at_2012-09-29%2021:52:02%20UTC/large.jpg?1348955522
Therefore I got a wrong url.
Are there any ways I can do that by configuring paperclip? Thanks!
As described here : https://github.com/thoughtbot/paperclip#defaults , you can change the default config, in your case I guess you want to change the :local_root so it doesn't include the app name.

Devise:: Cannot create user through rake db:seed (failure confirmation_instructions)

User model has a function
def self.createadmin(
User.create(:email => "abc#gmail.com", :password => "123456e", :password_confirmation => "123456e", :terms_of_service => '1')
end
In rake db:seed, I have to call User.createadmin
However, this fails
ActionView::Template::Error: ActionView::Template::Error
from /Users/bever/Projects/tr/app/views/devise/mailer/confirmation_instructions.html.erb:3:in `_app_views_devise_mailer_confirmation_instructions_html_erb___1974818942364630283_2154906860'
Then I changed the code in createadmin
begin
User.create(:email => "abc#gmail.com", :password => "123456e", :password_confirmation => "123456e", :terms_of_service => '1')
rescue => e
User.create(:email => "abc#gmail.com", :password => "123456e", :password_confirmation => "123456e", :terms_of_service => '1')
end
It works! Any clue why this is happening?
Have you tried seeding from the db/seeds.rb file instead of the model? When you try to do it on the model, devise is probably trying to send the conformation mail.
You should create your admin user on the seeds.rb file like this
User.create(:email => "abc#gmail.com", :password => "123456e", :password_confirmation => "123456e", :terms_of_service => '1')
Remember that if you are using confirmable module of devise you should add this field to the query.
:confirmed_at => Time.now
Maybe you should add the confirmation tokens and other fields useful to administrate your admin account via your rails app and not on the console.
PD: Probably if you post more of the error shown and maybe the line in the view I can help you more.
Greetings

Paperclip + Rails 3 + ActionMailer (receive) + s3

I am trying to save an image attachment sent to my rails app to s3 using paperclip however I am hitting these problems:
Its getting to the attachment loop and failing with a
NoMethodError (undefined method `size' for #<Mail::Part:
0x2b62856e8030>):
app/mailers/user_mailer.rb:23:in `receive'
app/mailers/user_mailer.rb:14:in `each'
app/mailers/user_mailer.rb:14:in `receive'
app/controllers/emails_controller.rb:10:in `create'
which is line
:photo_file_size => attachment.size,
commenting out that line, i hit this error when it tries to create:
NoMethodError (undefined method `to_tempfile' for #<Mail::Part:
0x2ac5eb944220>):
Here is my code below.
Appreciate the help..
class UserMailer < ActionMailer::Base
def receive(email)
#user = User.find_or_create_by_email(
#:name => FIXME,
:email => email.from,
:password => 'password',
:password_confirmation => 'password'
)
#item = Item.create(:title => email.subject, :user => #user, :price => 50)
if email.has_attachments?
for attachment in email.attachments
#item.photos.create(
:photo => attachment,
:photo_file_name => attachment.original_filename,
:photo_content_type => attachment.content_type,
:photo_file_size => attachment.size,
:photo_updated_at => Time.now.to_datetime)
#item.photos << attachment
end
end
end
end
Doing an inspect on my attachment object gives me this:
#<Mail::Part:23597877753640, Multipart: false, Headers: <Date: Wed, 25 Aug 2010 16:55:07 -0700>, <Mime-Version: 1.0>, <Content-Type: image/JPG; name="photo.jpeg">, <Content-Transfer-Encoding: base64>, <Content-Disposition: inline; filename=photo.jpeg>, <Content-ID: <4c75ad5b3cbed_52fe15764b0bf938695a#railgun64.30856.mail>>>
I experienced the same issue with rails 3.0.0 + paperclip + ActionMailer. I was able to work around the issue (ugly but working) by:
if mail_message.has_attachments?
for attachment in mail_message.attachments
tempfile=File.open(attachment.original_filename,'w')
tempfile.write_nonblock(attachment.body)
asset = Asset.new(:photo => File.open(tempfile))
asset.save!
tempfile.close
end
end
I did a short blog post on this here at http://minimul.com/full-proof-attachment-size-in-rails-3.html
In short do this
photo_file_size => defined?(attachment.decoded) ? attachment.decoded.length : attachment.size,