Reputation:
How could I attach a file to mail using form_for? So far it gives me an error:
ActiveRecord::StatementInvalid in UsersController#create
NoMethodError: undefined method `name' for nil:NilClass: INSERT INTO "users" ("created_at", "email", "file_field", "name", "text_field", "updated_at") VALUES (?, ?, ?, ?, ?, ?)
This is what I came up with.
class UserMailer < ActionMailer::Base
default :from => "[email protected]"
def registration_confirmation(user)
@user = user
unless user[:file_field].nil?
file=user[:file_field]
attachments[file.original_filename] = File.open(file.path, 'rb'){|f| f.read}
end
mail(:to => user.email, :subject => "Registered")
end
end
View
<%= form_for @user, :html => {:multipart => true} do |f| %>
<div class="field">
<%= f.label :file_field %><br />
<%= f.file_field :file_field %>
</div>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :email %><br />
<%= f.text_field :email %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
Create action
def create
@user = User.new(params[:user])
if @user.save
UserMailer.registration_confirmation(@user).deliver
redirect_to @user
else
render action: "new"
end
end
Upvotes: 3
Views: 882
Reputation: 185
This is a hot topic on stackoverflow, be sure to check out the other threads. They're really indepth, and should solve your problem.
E.g: Solution 1, Solution 2, Solution 3
If this doesn't turn out, come back and we'll be sure to fire up another mail-attachment thread.
Upvotes: 1