rails6 viewからcontrollerにget方式とpost方式でデータを渡す

rails6 viewからcontrollerにget方式とpost方式でデータを渡す

rails6でviewからcontrollerにget方式とpost方式でデータを渡すまでの手順を記述してます。Railsのバージョンは6.1.1を使用してます。

環境

  • OS CentOS Linux release 7.9.2009 (Core)
  • Ruby 2.7.2
  • Rails 6.1.1
  • rbenv 1.1.2-40-g62d7798

controller作成

まずは、「disp」という名前でcontrollerを作成します。

rails g controller disp

「app/controllers」配下に「disp_controller.rb」が作成されます。

view作成

「app/views/disp」配下に「index.html.erb」を作成します。

get方式

それでは、viewからcontrollerにget方式で実際に値を渡します。

「DispController」を以下の通り編集して、インスタンス変数「@str」を作成して、params[:str]でパラメーターを受け取り、値がなければ「”hello world”」とします。

class DispController < ApplicationController
  def index
    # params[:str]でパラメーターを受け取る
    @str = params[:str] ? params[:str] : "hello world"
  end
end

「index.html.erb」では、get方式で値を渡すため、以下のように編集します。

<%= @str %>
<a href="/disp?str=hello rails">hello rails</a>

「config」配下にある「routes.rb」にも以下を追加しておきます。

get "disp", to: "disp#index"

これでrailsを起動すると

rails s

ブラウザから http://localhost:3000/disp にアクセスすると、初めは「hello world」が表示され、get方式で値を渡したあとは「hello rails」表示されていると思います。

post方式

次に、viewからcontrollerにpost方式で実際に値を渡します。

「DispController」は、そのままにしておきます。

class DispController < ApplicationController
  def index
    # params[:str]でパラメーターを受け取る
    @str = params[:str] ? params[:str] : "hello world"
  end
end

「index.html.erb」では、post方式で値を渡すため、以下のように編集します。

<%= @str %>
<form action="/disp" method="POST">
    <input type="hidden" name="authenticity_token" value="<%= form_authenticity_token %>" />
    <input type="text" name="str" />
    <input type="submit" />
</form>

「config」配下にある「routes.rb」にも以下を追加しておきます。

post "disp", to: "disp#index"

ブラウザから http://localhost:3000/disp にアクセスすると、初めは「hello world」が表示され、post方式で値を渡した値が表示されていると思います。