LoginSignup
0
0

More than 1 year has passed since last update.

Railsのアクション内で実行される「redirect_to」にて、クエリストリングを渡す方法

Last updated at Posted at 2022-11-13

バージョン

  • Rails 6.1.7
  • ruby 3.1.2p20 (2022-04-12 revision 4491bb740a) [x86_64-linux]

状況

controller内の処理にて、リダイレクトするときにクエリストリングが渡したい。

class SessionController < ApplicationController
  def create
    # ... 処理

    redirect_to xxx_url # ここでクエリパラメータを渡したい
  end
end

結論

上記のようにxxx_urlを使った場合、キーワード引数として値を渡してもうまく反映されない。

class SessionController < ApplicationController
  def create
    # ... 処理

    redirect_to xxx_url, hogehoge: "fugafuga"
    # もちろんこんな形でも無理
    # redirect_to xxx_url, params: { hogehoge: "fugafuga" }
  end
end

なので、controllerとactionを指定してあげる形で記述する

class SessionController < ApplicationController
  def create
    # ... 処理

    # topicコントローラーのnewへとリダイレクトしたい場合
    redirect_to controller: "topic", action: "new", hogehoge: "fugafuga"
  end
end

当たり前かもしれないですが、同じcontroller内の別actionにリダイレクトしたい場合は、controllerの指定は不要です。

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