scaffoldで簡単お問い合わせ機能
rails db:create rails new ののち。。
$ rails g scaffold Contact name:string email:string content:text
ファイルがいっぱいできる。
Running via Spring preloader in process 17820 invoke active_record create db/migrate/20171118042216_create_contacts.rb create app/models/contact.rb invoke test_unit create test/models/contact_test.rb create test/fixtures/contacts.yml invoke resource_route route resources :contacts invoke scaffold_controller create app/controllers/contacts_controller.rb invoke erb create app/views/contacts create app/views/contacts/index.html.erb create app/views/contacts/edit.html.erb create app/views/contacts/show.html.erb create app/views/contacts/new.html.erb create app/views/contacts/_form.html.erb invoke test_unit create test/controllers/contacts_controller_test.rb invoke helper create app/helpers/contacts_helper.rb invoke test_unit invoke jbuilder create app/views/contacts/index.json.jbuilder create app/views/contacts/show.json.jbuilder create app/views/contacts/_contact.json.jbuilder invoke test_unit create test/system/contacts_test.rb invoke assets invoke coffee create app/assets/javascripts/contacts.coffee invoke scss create app/assets/stylesheets/contacts.scss invoke scss create app/assets/stylesheets/scaffolds.scss
マイグレーションはする必要がある。
rails db:migrate
メイラーを作成
rails g mailer ContactMailer
mailers/contact/mailer.rbに追記。 contact_mailメソッドにおいて引数を受け取っている。 インスタンス変数は、view(メール本文)で使用するために定義している。
class ContactMailer < ApplicationMailer def contact_mail(contact) @contact = contact mail to:"自分のメールアドレス",subject:"お問い合わせの確認メール" end end
メイラーのviewを作成 ・これは、送信されるメールの本文です。 (app/views/contact_mailer/contact_mail.html.erb)
<h1>お問い合わせが完了しました。</h1> <h4>name:<%= contact.name %></h4> <h4>お問い合わせ内容の確認</h4> <p>content:<%=@contact.content %></p>
お問い合わせをした時にメイラーが呼び出されるように実装。 ・redirect_toにパスではなくインスタンス変数を渡している。これをrailsで勝手に判断してshowを表示してくれる。 ・ここではjsonは特に使用していない。
# POST /contacts # POST /contacts.json def create @contact = Contact.new(contact_params) respond_to do |format| if @contact.save ContactMailer.contact_mail(@contact).deliver#追記 format.html { redirect_to @contact, notice: 'Contact was successfully created.' } format.json { render :show, status: :created, location: @contact } else format.html { render :new } format.json { render json: @contact.errors, status: :unprocessable_entity } end end end
(まとめ) 1.contacts_controllerのcreateアクションでお問い合わせをデータベースに保存する処理が流れる。
2.1の処理が流れた時ContactMailer.contact_mail(@contact).deliverのメイラーの処理が走り、app/mailers/contact_mailer.rbのcontact_mailメソッドが呼び出される。
3.引数として渡す@contactをcontact_mail(contact)の記述でcontactという引数名で受け取り、contact_mail内の処理が実行される。メソッド内で@contact = contactとしているのは@contactをView(contact_mail.html.erb)で使用するため。
4.処理が一通り流れ、メールがお問い合わせ者に届き、contact_mail.html.erbで記述されているHTMLが表示される。
インスタンス変数が効く範囲の理解が怪しい。