LoginSignup
34
56

More than 5 years have passed since last update.

シンプルにお問い合わせ機能を実装する

Last updated at Posted at 2018-11-16

お問い合わせ機能を実装する

めちゃくちゃ苦戦してしまったので備忘録を置いておきます。
Railsのバージョンは5.0.7
herokuでデプロイしてる。
バージョンの都合でform_with使った方がいいところをform_forにしているので悪しからず。
基本Railsチュートリアルを参考に実装していますが、色んな方のgithubを見て回ったので「あ、ここパクられてる」という方がいるかと思いますが、そういう方には本当に感謝しております。

メールの送信に最低限必要となるもの
1.アクションメーラー
2.問い合わせ用のモデル
3.問い合わせ用のコントローラー
4.問い合わせフォーム用のビュー

モデル、コントローラー、メーラーの準備

$ rails g mailer ContactMailer contact_mail 

$ rails g model Contact email:string message:text

$ rails g controller contacts new create 

rails db:migrateしてcontactsテーブルを作成。
問い合わせする側の情報としては返信先のアドレスと問い合わせ内容だけで充分かと思うけど、場合によっては名前なんかも付け足す。
モデルの方はバリデーションを付与するだけなので先に終わらせてしまう。

contact.rb
class Contact < ApplicationRecord
  validates :email, presence: true, length: {maximum:255},
                    format: {with: /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i}
  validates :message, presence: true
end

rails g mailer~でいくつかファイルが自動生成されている。

app/mailers/applicaton_mailer.rb
app/mailers/contact_mailer.rb
上記二つが自動生成されている。
一個ずつ見ていく。

application_meiler.rb
class ApplicationMailer < ActionMailer::Base
  default from: 'from@example.com'
  layout 'mailer'
end

default from:~は送信先。
問い合わせ内容がここのアドレスから送られてくる。
アドレスがこのままでよければここは触らないでOK

contact_mailer.rb
class ContactMailer < ApplicationMailer

  def contact_mail(contact)
    @contact = contact  
    mail to: ENV['MAIL'], subject: "メールのタイトル"
  end
en

メールの生成と送信を行うcontact_mailメソッドを作成する。
mailがメール生成のためのメソッドになる。
to: で送信先のアドレスを指定。
subjectでメールのタイトルを指定。
ちなみに直接送信先のアドレスを書いてgithubに上げると個人のアドレスがばれてしまう。それで問題にならないよう環境変数を使う。
以下に代入方法。

$ heroku config:set 環境変数=値

次にメールのフォーマットを作成する。
これもメーラーを作成した時に自動生成されている。
app/views/contact_mailer/contact_mail.text.erb

contact_mailer.rbで定義したcontact_mail(contact)内の変数を使っている……のだと思う。

contact_mail.html.erb
<h3>お問い合わせ内容</h3>

------------------------------------------------
<p>email: <%= @contact.email %></p>

<p>content: <%= @contact.message %></p>

------------------------------------------------

次にコントローラー。

contacs_controller.rb
class ContactsController < ApplicationController
  def new
    @contact = Contact.new
  end

  def create
    @contact = Contact.new(contact_params)
    if @contact.save
      ContactMailer.contact_mail(@contact).deliver
      flash[:success] = 'お問い合わせを受け付けました'
      redirect_to root_path
    else
      render :new
    end
  end

  private

  def contact_params
    params.require(:contact).permit(:email, :message)
  end
end

空のインスタンスをビューに渡して、それを使ってcreateアクションを呼び出すいつもの流れ。ストロングパラメーターもいつも通りに設定する。

以上でメーラー、モデル、コントローラーは終了

問い合わせフォームの実装

viewはnew.html.erbだけで十分。
create.html.erbが自動生成されていると思うので削除しておく。

new.html.erb
<%= form_for @contact do |f| %>

  <div class="form-group">
    <%= f.label :email, '返信先メールアドレス' %>
    <%= f.text_field :email, class: 'form-control' %>
  </div>

 <div class="form-group">
   <%= f.label :message, 'お問い合わせ内容' %>
   <%= f.text_area :message, size: '10x10', class: 'form-control' %>
 </div>

  <%= f.submit '送信' %>

<% end %>

これで正常にビューが表示されれば大丈夫だとは思う。

SendGridを適用する

SendGridというherokuアドオンを使用してメールを送信する。
このアドオンを使用するにはherokuにクレジットカードを登録しなくちゃいけないらしいので登録しておく。
SendGridは一日400通までという制限があるが、利用は無料らしい。

$ heroku addons:create sendgrid:starter

これを使うために、production環境にsmtp情報を書き込む。

production.rb.rb

  config.action_mailer.raise_delivery_errors = true
  config.action_mailer.default_url_options = { host: 'アプリ名.herokuapp.com' }
  ActionMailer::Base.delivery_method = :smtp
  ActionMailer::Base.smtp_settings = {
    user_name: ENV['SENDGRID_USERNAME'],
    password: ENV['SENDGRID_PASSWORD'],
    domain: "heroku.com",
    address: "smtp.sendgrid.net",
    port: 587,
    authentication: :plain,
    enable_starttls_auto: true
    }
  config.action_mailer.perform_caching = false

ENV['SENDGRID_USERNAME']と ENV['SENDGRID_PASSWORD']の二つの環境変数が使われているが、これはSendGridアドオンが用意してくれてる環境変数なので特に気にしなくて良い。

ここまででデプロイしてheroku run rails db:migrateすればメールが送られる、はず。

初心者ですので、間違いなどあればご教授お願いします。

34
56
0

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
34
56