LoginSignup
1
0

More than 3 years have passed since last update.

Ruby on Rails パラメータ付き遷移処理の方法

Last updated at Posted at 2019-11-23

概要

遷移元のテキストボックスに入力した内容を、遷移先の画面に表示します。

画面イメージ

遷移元

qiita_sc_1.png

遷移先


qiita_sc_2.png

プログラム:共通

ルーティングを設定します。
moveアクションが遷移するアクションです。
indexアクションで遷移元で入力された値を受け取ります。
:nameがパラメーターで、入力された値が入っています。

routes.rb
Rails.application.routes.draw do
  post 'move' => 'home#move'
  get  'second/:name' => 'second#index'
end

プログラム:遷移元

form_tag内にアクション名「move」を設定し、
text_field_tagのパラメーターを「name」にします。
これで、button_toで生成されたbuttonを押下すると、
遷移する際に、テキストボックスに入力された値を渡すことができます。

遷移元.html.erb
<h3>画面1</h3>
<div>
  <%= form_tag("move")do %>
    <%= text_field_tag "name"%>
    <%= button_to 'Button'%>
  <% end %>
</div>

controller内では、redirect_toで遷移先のパスと、
テキストボックスで入力された値をパスに入力し、遷移させます。

遷移元_controller.rb
class HomeController < ApplicationController
  def top
  end
  def move
    redirect_to("/second/#{params[:name]}");
  end
end

プログラム:遷移先

変数名「@name」に代入されている値を表示しています。

遷移先.html.erb
<h3>画面2</h3>
名前は<%= @name %>です。

params[:name]で、遷移元で入力された値を取得し、htmlに表示する変数に代入します。

遷移先_controller.rb
class SecondController < ApplicationController
  def index
    @name = params[:name]
  end
end
1
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
1
0