Tag: Rails3/問い合わせフォーム
class Contact include ActiveModel::Validations include ActiveModel::Conversion extend ActiveModel::Naming attr_accessor :name, :email, :subject, :message validates :name, :presence => true # confirmation?が必要 validates :email, :presence => true, :format => { :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i } validates :subject, :presence => true validates :message, :presence => true def initialize(attributes = {}) attributes.each do |name, value| send("#{name}=", value) end end def persisted? false end end
class Message < ActionMailer::Base include ApplicationHelper default from: "noreply@example.com" def new_contact(contact) @contact = contact mail(:to => "tom@example.com", :subject => "[Contact Us] #{contact.subject}") end end
Name: <%= @contact.name %> Email: <%= @contact.email %> Subject: <%= @contact.subject %> Message: <%= @contact.message %>
<%= form_for(@contact, :url => about_create_path, :html => {:class =>'form-inline'}) do |f| %> <% if @contact.errors.any? %> <div id="error_explanation"> <h2>エラーが発生しました :</h2> <ul> <% @contact.errors.full_messages.each do |msg| %> <li><%= msg %></li> <% end %> </ul> </div> <% end %> <table class="table table-bordered table-condensed"> <tr> <th class="span2">お名前</th> <td><%= f.text_field :name, {:class => 'span6'} %></td> </tr> <tr> <th class="span2">メール</th> <td><%= f.text_field :email, {:class => 'span6'} %></td> </tr> <tr> <th class="span2">題名</th> <td><%= f.text_field :subject, {:class => 'span6'} %></td> </tr> <tr> <th class="span2">内容</th> <td> <%= f.text_area :message, {:rows => 6, :class => 'span6'} %> </td> </tr> </table> <p> <span style="width:200px;"> <%= f.submit '送信', :name => 'save_button', :class=>'btn btn-primary' %> </span> </p> <% end %>
class ContactsController < ApplicationController def new @contact = Contact.new end def create @contact = Contact.new(params[:contact]) if @contact.valid? Message.new_contact(@contact).deliver redirect_to(root_path, :notice => "Message was successfully sent.") else flash.now.alert = "Please fill all fields." render :new end end end
match 'contact' => 'contacts#new', :as => 'contacts', :via => :get match 'contact' => 'contacts#create', :as => 'contacts', :via => :post