0
0

More than 3 years have passed since last update.

返信機能実装時、工夫した点 -newアクション-

Posted at

投稿に対する返信機能を作成する際に、newアクションの実装を少し工夫することで便利にすることができました。

●実装コード

Q&Aサイトを実装しているため、投稿=Question 返信=Answerとなっています。

app/contorollers/answers_controlelr.rb
  def new
    @question = Question.find(params[:id])
    @answer = @question.answers.build
  end
config/routes.rb
  get  "/answers/:id", to: "answers#new", as: :new_answer
  resources :answers, except: %i(new)

●解説

1.アソシエーションでquestionを取得することができる。

app/contorollers/answers_controlelr.rb
  def new
    @question = Question.find(params[:id])
    @answer = @question.answers.build
  end

こうすることで、@answer = @question.answersとすることで、@answer.questionのような形で、questionを取得することができます。例えば下記のように活用したり。

app/contorollers/answers_controlelr.rb
def create
redirect_to question_path(@answer.question)

2.@questionを取得することで、"answers/new" ページに質問の内容を記載することができる。

get  "/answers/:id", to: "answers#new", as: :new_answer
  resources :answers, except: %i(new)

こうすることで、/new/:question_id とすることができます。
この記述がないと、/new.question_id となってしまい、パラメーターを渡すことができません。

●まとめ

あくまで自分はポートフォリオを作成している段階のレベル感です。
もっと良い実装方法や誤りがありましたら、指摘して頂けますと大変助かります。

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