LoginSignup
80
80

More than 5 years have passed since last update.

[Rails 4.1] ActiveModelを使って、DBと関係ないFormを作り、確認画面付きのお問い合わせフォームを作る方法

Last updated at Posted at 2014-11-11

はじめに

ユーザーからのお問い合わせフォームを出す為に、お問い合わせ内容がActionMailerで届くような感じのものを作りたいと思います。
かなりあっさりできます。

ActionMailerの設定

ActionMailerで、Gmailの設定をする場合は以下の感じにしました。

  # ActionMailer
  config.action_mailer.default_url_options = { :host => 'localhost:3000' }
  config.action_mailer.raise_delivery_errors = true
  config.action_mailer.delivery_method = :smtp
  config.action_mailer.smtp_settings = {
    #:enable_starttls_auto => false,
    :address => 'smtp.gmail.com',
    :port => 587,
    :domain => 'gmail.com',
    :authentication => :plain,
    :user_name => 'mailaddress',
    :password => 'passwrod'
  }

/config/routes.rb

# お問い合わせ
  get  'inquiry'         => 'inquiry#index'
  post 'inquiry/confirm' => 'inquiry#confirm'
  post 'inquiry/thanks'  => 'inquiry#thanks'

/app/controllers/inquiry_controller.rb

class InquiryController < ApplicationController
  def index
    @inquiry = Inquiry.new
    render :action => 'index'
  end

  def confirm
    @inquiry = Inquiry.new(inquiry_params)
    if @inquiry.valid?
      render :action => 'confirm'
    else
      render :action => 'index'
    end
  end

  def thanks
    @inquiry = Inquiry.new(inquiry_params)
    # send mail
    InquiryMailer.received_email(@inquiry).deliver

    flash[:notice] = "お問い合わせ頂き、ありがとうございました。"
    render :action => 'thanks'
  end

  private
  def inquiry_params
    params.require(:inquiry).permit(:name, :email, :message)
  end

end

View

3つ作ります。

  • app/views/inquiry/index.html.erb
  • app/views/inquiry/confirm.html.erb
  • app/views/inquiry/thanks.html.erb
index.html.erb
    <%= form_for @inquiry, :url => inquiry_confirm_path do |f| %>

      <% if @inquiry.errors.any? %>
        <div class="alert alert-danger" role="alert">
          <strong>入力内容にエラーがあります</strong>
          <ul>
            <% @inquiry.errors.each do |attr, msg| %>
              <li><%= msg %></li>
            <% end %>
          </ul>
        </div>
      <% end %>

        <table class="table">
          <tr>
            <th>名前<span class="text-danger">(必須)</span></th>
            <td><%= f.text_field :name %></td>
          </tr>
          <tr>
            <th>メールアドレス<span class="text-danger">(必須)</span></th>
            <td><%= f.text_field :email %></td>
          </tr>
          <tr>
            <th>お問い合わせ内容<span class="text-danger">(必須)</span></th>
            <td><%= f.text_area :message %></td>
          </tr>
        </table>
        <%= f.submit '確認', class: 'btn btn-primary' %>
    <% end %>
confirm.html.erb
    <h1>お問い合わせ内容確認</h1>

    <%= form_for @inquiry, :url => inquiry_thanks_path do |f| %>
      <table>
        <tr>
          <th>名前</th>
          <td>
            <%= f.hidden_field :name %>
            <%= @inquiry.name %>
          </td>
        </tr>
        <tr>
          <th>メールアドレス</th>
          <td>
            <%= f.hidden_field :email %>
            <%= @inquiry.email %>
          </td>
        </tr>
        <tr>
          <th>お問い合わせ内容</th>
          <td>
            <%= f.hidden_field :message %>
            <%= simple_format(@inquiry.message) %>
          </td>
        </tr>
      </table>
      <%= f.submit '送信', :class => 'btn btn-primary' %>
    <% end %>
thanks.html.erb
    <h1>お問い合わせ完了</h1>
    <p>以下の様に承りました。</p>
    <table>
      <tr>
        <th>名前</th>
        <td>
          <%= @inquiry.name %>
        </td>
      </tr>
      <tr>
        <th>メールアドレス</th>
        <td>
          <%= @inquiry.email %>
        </td>
      </tr>
      <tr>
        <th>お問い合わせ内容</th>
        <td>
          <%= simple_format(@inquiry.message) %>
        </td>
      </tr>
    </table>

app/model/inquiry.rb

class Inquiry
  include ActiveModel::Model #ここでActiveModelを読み込んで、DBと繋がらないモデルとしている

  attr_accessor :name, :email, :message #これ大事

  validates :name, :presence => {:message => '名前を入力してください'}
  validates :email, :presence => {:message => 'メールアドレスを入力してください'}
  validates :message, :presence => {:message => 'お問い合わせ内容を記載して下さい'}
end

Mailer

app/mailer/inquiry_mailer.rb

class InquiryMailer < ActionMailer::Base
  default to: "送信先メアド" 
  default from: "送信元メアド"

  def received_email(inquiry)
    @inquiry = inquiry
    mail(:subject => 'ユーザーに配信されるメールのタイトル')
  end

end

/app/views/inquiry_mailer/received_email.text.erb

運営側に届くメールのテンプレです。

Webサイトからお問い合わせがありました。

--------------------------
Name:<br>
<%= @inquiry.name %>
Email:<br>
<%= @inquiry.email %>
Message:<br>
<%= @inquiry.message %>
--------------------------

コマンドラインからpryでテスト

$ rails c
[1] pry(main)> inquiry = Inquiry.new(name: "name", email: "hogehoge@gmail.com", message: "message")
#<Inquiry:0x007f532c0faa38 @name="name", @email="hoge@gmail.com", @message="message">
[2] pry(main)> InquiryMailer.received_email(inquiry).deliver
  Rendered inquiry_mailer/received_email.text.erb (2.9ms)

InquiryMailer#received_email: processed outbound mail in 22.1ms

Sent mail to 送信先メアド (9389.4ms)
Date: Tue, 01 Jan 2013 05:40:00 +0000
From: 送り元メアド
To: 送信先メアド
Message-ID: <5461a13021468_13f53fa990a693d876925>
Subject: =?UTF-8?Q?=E?=
Mime-Version: 1.0
Content-Type: text/plain;
 charset=UTF-8
Content-Transfer-Encoding: base64


#<Mail::Message:69997598397020, Multipart: false, Headers: <Date: Tue, 11 Nov 2014 05:40:00 +0000>, <From: 送信元>, <To: 送信先>, <Message-ID: <5461a13021468_13f53fa990a693d876925>>, <Subject: タイトル>, <Mime-Version: 1.0>, <Content-Type: text/plain>, <Content-Transfer-Encoding: base64>>

あっさり!

References

https://www.imd-net.com/column/1731/
http://tanihiro.hatenablog.com/entry/2014/01/09/193720
http://easyramble.com/rails-action-mailer.html
http://qiita.com/jnchito/items/94f3ad15128f88bf89d6

80
80
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
80
80