Railsでパラメータを受け取ってみる

RailsでHello, world!を表示してみるの続き

Railsで送られてきたパラメータを受けっとてみる。

params

URLから送られてきた値やフォームで入力した値はparamsに格納される。

試しに、paramsの中身を表示してみる。

$ vi app/controllers/sample_controller.rb
class SampleController < ApplicationController
  def index
    render :text => params
  end
end

http://サーバーのアドレス/
にアクセスすると、

{"controller"=>"sample", "action"=>"index"}

が表示される

routesのパラメータ

routes.rbに下記のように指定すると、:aaaや:bbb,:cccに指定した値がparamsに格納される。

$ vi config/routes.rb
Sample::Application.routes.draw do
  root 'sample#index'
  get 'sample/index/:aaa/:bbb/:ccc' => 'sample#index'
end

http://サーバーのアドレス/sample/index/100/200/300
にアクセスすると

{"controller"=>"sample", "action"=>"index", "aaa"=>"100", "bbb"=>"200", "ccc"=>"300"}

が表示される。

GETパラメータ

URLにクエリの形式で指定されたパラメタも、paramsに設定される。

http://サーバーのアドレス/?aaa=400&bbb=500&ccc=600
にアクセスすると

{"aaa"=>"400", "bbb"=>"500", "ccc"=>"600", "controller"=>"sample", "action"=>"index"}

が表示される。

POSTパラメータ

POSTのパラメータもparamsに設定される。

indexを空にしてviewを表示するようにし、

$ vi app/controllers/sample_controller.rb
class SampleController < ApplicationController
  def index
  end
end

viewを下記のように修正する。
(paramsはviewでも参照できる)

$ vi app/views/sample/index.html.erb
<%= params %>

<%= form_tag('/sample/index') do %>
  <input type="text" name="aaa" /><br />
  <input type="text" name="bbb" /><br />
  <input type="text" name="ccc" /><br />
  <input type="submit" value="send">
<% end %>

今のままだとPOSTのパラメタが受け取れないので、
http://サーバーのIPアドレス/sample/index
にPOSTできるようroutes.rbを修正する。

$ vi config/routes.rb
Sample::Application.routes.draw do
  root 'sample#index'
  post 'sample/index' => 'sample#index'
end

http://サーバーのIPアドレス/
にアクセスして、何かフォームに適当に入力して[send]ボタンを押すと

{"utf8"=>"✓", "authenticity_token"=>"・・・", "aaa"=>"700", "bbb"=>"800", "ccc"=>"900", "controller"=>"sample", "action"=>"index"}

のような表示になる。

配列での受け取り

nameのところを下記のように配列にすると、paramsに配列で設定される。

$ vi app/views/sample/index.html.erb
<%= params %>

<%= form_tag('/sample/index') do %>
  <input type="text" name="ddd[]" /><br />
  <input type="text" name="ddd[]" /><br />
  <input type="text" name="ddd[]" /><br />
  <input type="submit" value="send">
<% end %>

http://サーバーのIPアドレス/
にアクセスして、何かフォームに適当に入力して[send]ボタンを押すと

{"utf8"=>"✓", "authenticity_token"=>"・・・=", "ddd"=>["700", "800", "900"], "controller"=>"sample", "action"=>"index"}

のような表示になる。


nameのところを下記のようにハッシュにすると、paramsにハッシュで設定される。

$ vi app/views/sample/index.html.erb
<%= params %>

<%= form_tag('/sample/index') do %>
  <input type="text" name="eee[aaa]" /><br />
  <input type="text" name="eee[bbb]" /><br />
  <input type="text" name="eee[ccc]" /><br />
  <input type="submit" value="send">
<% end %>

http://サーバーのIPアドレス/
にアクセスして、何かフォームに適当に入力して[send]ボタンを押すと

{"utf8"=>"✓", "authenticity_token"=>"・・・", "eee"=>{"aaa"=>"700", "bbb"=>"800", "ccc"=>"900"}, "controller"=>"sample", "action"=>"index"}

のような表示になる。