-
-
Save mklickman/1790914 to your computer and use it in GitHub Desktop.
<%= form_for(@contact) do |f| %> | |
<% if @contact.errors.any? %> | |
<div id="error_explanation"> | |
<h3><%= pluralize(@contact.errors.count, "error") %> prohibited this contact from being saved:</h2> | |
<ul> | |
<% @contact.errors.full_messages.each do |msg| %> | |
<li><%= msg %></li> | |
<% end %> | |
</ul> | |
</div> | |
<% end %> | |
<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="field"> | |
<%= f.label :message %><br /> | |
<%= f.text_area :message %> | |
</div> | |
<div class="actions"> | |
<%= f.submit "Send"%> | |
</div> | |
<% end %> |
class Contact < ActiveRecord::Base | |
validates :email, | |
:presence => :true, | |
:format => { | |
:with => /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i, | |
:message => "must be a valid email address" | |
} | |
validates :message, :presence => :true | |
end |
class ContactsController < ApplicationController | |
def new | |
@contact = Contact.new | |
end | |
def create | |
@contact = Contact.new(params[:contact]) | |
if @contact.save | |
ContactsMailer.general_message(@contact).deliver | |
render :thanks | |
else | |
render :new | |
end | |
end | |
def thanks | |
end | |
end |
# This file lives in the app/mailers directory | |
# See http://guides.rubyonrails.org/action_mailer_basics.html for details | |
class ContactsMailer < ActionMailer::Base | |
default from: "[email protected]" | |
def general_message(contact) | |
@contact = contact | |
mail( :to => "[email protected]", :subject => "You Have a Message From Your Website") | |
end | |
end |
<h2>Send Us A Message</h1> | |
<%= render 'form' %> |
Yeah, you need the format block with a "format.js" line, and a view file called "create.js.erb" or whatever your controller action and template language is. Otherwise theres no js to handle the remote request.
I think I finally understood what to do. My file (create.js.erb) looks kind of like this:
<% if @message.errors.any? -%>
console.log('errors')
<% else -%>
console.log('good to go')
<% end -%>
Seem reasonable to you?
Far as I know, that should work. Think of .js view files the same way you would as a script tag with the src attribute set to a javascript file. The only difference is that that code would only work against the like-named html.erb file. Basically, you have the right idea. Let me know if that works or not.
Yes, I see what you mean. It did work!
It did! Still kinda buggering around with my response block though... I'm gonna need respond_to do |format|, right?