前提・実現したいこと
プログラミング勉強中。始めて1ヶ月の初心者です。
何卒宜しくお願いいたします。
(Ruby on Rails使用)
1人のユーザーが決められた質問(複数用意)に対して答えを入力していく。
1人のユーザーが1つの質問に対して行える回答は1回のみとさせる。
1つの質問に対する詳細ページで、ユーザー(ログインユーザー)が自分が行った質問に対する回答を確認することができる。
一度回答した質問をクリックすると、newアクションのフォーム入力画面ではなく,showアクションの詳細画面が表示されるようにしたい。
発生している問題・エラーメッセージ
一度回答した質問をクリックすると、newアクションのフォーム入力画面ではなく,showアクションの詳細画面が表示されるようにしたい。
↑この実装で if 文を使用して条件定義すれば良いかと思うが、その記述が分からない。
if データ(そのユーザーによって行われた1つの質問に対する回答)がある場合
詳細ページは
else
入力ページへ
end
こちらを定義したい。
もしくはその逆を定義したい。
該当のソースコード
[routes.rb]
ruby
1 2 3Rails.application.routes.draw do 4 devise_for :users 5 root "groups#index" 6 resources :users, only: [:edit, :update] 7 resources :questions, only: [:index, :show] do 8 resources :answers, only: [:new, :create] 9 end 10end
[answer_controller.rb]
ruby
1 2 3 4class AnswersController < ApplicationController 5 6 def new 7 @question = Question.find(params[:question_id]) 8 @answer = Answer.new 9 # @answers = Answer.find_by(question_id: params[:id],user_id: current_user.id) 10 # if @answers == @answers.blank? 11 # render("answers/new") 12 # else 13 # render("questions/show") 14 # end 15 end 16 17 def create 18 @question = Question.find(params[:question_id]) 19 @answer = Answer.new( 20 answer: answer_params[:answer], 21 question_id: params[:question_id], 22 user_id: current_user.id 23 ) 24 25 if @answer.save 26 redirect_to questions_path 27 else 28 render :new 29 end 30 end 31 32 private 33 def answer_params 34 params.require(:answer).permit(:answer, :question_id) 35 end 36 37end
[question_controller.rb]
ruby
1 2 3class QuestionsController < ApplicationController 4 5 def index 6 @questions = Question.all 7 8 end 9 10 def show 11 @answer = Answer.find_by(question_id: params[:id],user_id: current_user.id) 12 end 13 14 private 15 def answer_params 16 params.require(:answer).permit(:answer, :question_id) 17 end 18 19end 20
[question/index.html.haml]
haml
1.body 2 = render 'groups/header' 3 .contents 4 .question 5 - @questions.each do |q| 6 .question__items 7 .question__items__item 8 =link_to new_question_answer_path(q.id), class:"question__items__item__box" do 9 = q.content 10 .question__items__show 11 = link_to question_path(q.id), class:"question__items__show__btn" do 12 = "・・・"
[question/show.html.haml]
ruby
1.body 2 = render 'groups/header' 3 .contents 4 .answer-box 5 %p.hoge 6 = "・#{@answer.answer} "
[answer/new.html.haml]
haml
1.body 2 = render 'groups/header' 3 .form 4 = form_for [@question, @answer], url: question_answers_path, method: :post do |f| 5 = f.text_area :answer, class: 'form__text', placeholder: "メモ → 抽象化 → 転用" 6 = f.submit 'SEND', class: 'form__btn'
試したこと
記述方法を検索し試してみるも思ったように実装ができない為、教えていただきたく思います。
分かりづらい説明になっているかもしれませんが、よろしくお願いいたします。
補足情報(FW/ツールのバージョンなど)
ruby バージョン 2.5.1
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2020/06/16 05:59