LoginSignup
0
1

条件分岐が可能な診断機能

Posted at

はじめに

当記事は、Ruby on Railsにおいて分岐が発生する診断機能を実装したい方へ向けたものです。
この記事でも診断機能は実装することが可能ですが、どんな選択肢を選んでも同じ質問を回答することで結果が出る仕組みのため、「1問目で選ぶ選択肢によって、2問目の質問を変えたい...」という場合、活用することが難しくなってしまいます。
主に以上の悩みを抱えている人に向けて、役に立てれば幸いです。

実装に使う知識、及び筆者が伝えたいこと

使う知識は「MVCの基本」。これだけです。新規ページを作り、遷移を活用して作っていくイメージです。きちんとMVCが理解できていれば、不可解な点はなく実装できると思います。
ここで筆者が伝えたいことは、基礎的な知識でも、使い方によっては大きなインパクトを発揮できることがプログラミングの面白さだということです。
あくまで個人の感想ですが、難しいことを身に着けることに執着してしまう傾向があるなら、今ある知識を活用する路線で考えてみても面白いかもしれません。
前置きが長くなりましたが、実装していきましょう!

1.全体像を見てみる

ページ遷移を多用するため、以下の画像のような遷移をするイメージを持っておくとわかりやすくなるかと思います。
また、この実装においてモデルの設計をほとんど使用しないため、既存のコントローラーにアクションを加えていく形でも問題ないはずです。
しかし、ページ数が多くなることが予想されるので、あえて新規作成するのもいいかもしれますん。
スクリーンショット (1066).png

2.Routing設計

route.rb

#省略
    get 'perfumes/question1' => 'perfumes#question1'
    get 'perfumes/question2' => 'perfumes#question2'
    get 'perfumes/question3' => 'perfumes#question3'
    get 'perfumes/question4' => 'perfumes#question4'
    get 'perfumes/show1' => 'perfumes#show1'
    get 'perfumes/show2' => 'perfumes#show2'
    get 'perfumes/show3' => 'perfumes#show3'
    get 'perfumes/show4' => 'perfumes#show4'
    get 'perfumes/show5' => 'perfumes#show5'
    get 'perfumes/show6' => 'perfumes#show6'
#省略

3.Controller設計

perfumes_controller.rb

#省略
    def question1
    end
    
    def question2
    end
    
    def question3
    end
    
    def question4
    end
    
    def show1
    end
    
    def show2
    end
    
    def show3
    end
    
    def show4
    end
    
    def show5
    end
    
    def show6
    end
#省略

4.view設計

perfumes/index.html.erb

<h1>診断機能 スタートページ</h1>

<%= link_to "診断する!", perfumes_question1_path %>

perfumes/question1.html.erb

<h1>1</h1>

<%= link_to "山派", perfumes_question2_path %>
<%= link_to "海派", perfumes_question3_path %>
<%= link_to "空派", perfumes_question4_path %>

perfumes/question2.html.erb

<h1>2 (パターン1)</h1>
<p>山にロマンを感じた瞬間を教えてください。</p>

<%= link_to "富士山にロマンを感じた", perfumes_show1_path %>
<%= link_to "険しい山道にロマンを感じた", perfumes_show2_path %>

perfumes/question3.html.erb

<h1>2 (パターン2)</h1>
<p>海は人間にとってどんな存在だと思うか教えてください。</p>

<%= link_to "時々人に牙をむくが、その荒々しさがかっこいい存在", perfumes_show3_path %>
<%= link_to "心を落ち着かせてくれる壮大な存在", perfumes_show4_path %>

perfumes/question4.html.erb

<h1>2 (パターン2)</h1>
<p>空を飛べるなら何をしたいか教えてください。</p>

<%= link_to "空から人間を見下ろして嘲笑う", perfumes_show5_path %>
<%= link_to "ただ気楽に、優雅に時を過ごしたい", perfumes_show6_path %>

perfumes/show1.html.erb

<h4><おすすめの俳句></h4>
<p>冷えびえと 袖に入る日や 秋の山 </p>
<%= link_to "トップに戻る", perfumes_path %>

※show2~show6はshow1と同様

以上です!

5.デモ動画

無題の動画 ‐ Clipchampで作成.gif

さいごに

一見煩雑そうに見えますが、使っている知識は初歩的です。
知識を活用していくプログラミングの楽しさを経験できることに、少しでも貢献できれば幸いです。

0
1
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
0
1