1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Rails】新規投稿時のリダイレクト先を条件分岐・分類(備忘録)

Last updated at Posted at 2022-02-01

みなさん、こんにちは!
筆者は大学生限定のプログラミングスクール「GeekSalon」でメンターをしています!
興味のある方や話だけでも聞いてみてい方はぜひのぞいてみてください👍

さっそく今回の本題に入っていきます!
今回は投稿の分類に応じて、新規投稿後のリダイレクト先を変更していきます。

私はこの記事の「カテゴリー分けその2」の方法を参考に投稿を分類するということをおこなったのですが、新規投稿完了後にリダイレクトするページがどのカテゴリを選んでも同じViewページに飛んでしまうため、カテゴリに応じてリダイレクト先のViewページも変更したいと思いそれを実装しました。今回はその方法残しておきます。

なお、投稿の分類は実装済みという前提で話を進めていくため、投稿の分類を実装していない場合は先ほどの記事を参考に実装したのち、こちらの記事をお読みください!。

##実装環境
ruby 2.7.4p191 (2021-07-07 revision a21a3b7d23) [x64-mingw32]
Rails 6.1.4.1

##実装① ~該当コントローラーのCreateアクションの記述を変更~

今回は参考とした記事に依拠して、dogとcatとhadakadebanezumiという3つの分類を行うことを想定して実装していきます。

やるべきことは以下の1つです。

Tweets_controller.rb
  def create
    tweet = Tweet.new(tweet_params)
    if tweet.save
記述個所
      if tweet.category = "dog"
        redirect_to :action => "dog"
      elsif tweet.category = "cat"
        redirect_to :action => "cat"
      elsif tweet.category = "hadakadebanezumi"
        redirect_to :action => "hadakadebanezumi"
      else
      end
記述個所
    else
      redirect_to :action => "new"
    end
  end

これだけです!
しかし、この条件分岐はもっと簡略化して記述することもできます。(以下参照)

Tweets_controller.rb
  def create
    tweet = Tweet.new(tweet_params)
    if tweet.save
記述個所
      case tweet.category
      when "dog"
        redirect_to :action => "dog"
      when "cat"
        redirect_to :action => "cat"
      when "hadakadebanezumi"
        redirect_to :action => "hadakadebanezumi"
      end
記述個所
    else
      redirect_to :action => "new"
    end
  end

これで終わりです!
モデル名・カラム名・カラムに収納されている値は作成するプロダクトに応じて変更してください!
以上で、新規投稿で選択したカテゴリに応じて、リダイレクト先のViewページを変更することができました。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?