4
4

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 5 years have passed since last update.

[Rails] params

Posted at

You will probably want to access data sent in by the user or other parameters in your controller actions. 
...
Rails does not make any distinction between query string parameters and POST parameters, and both are available in the params hash in your controller:

paramsはhashににており、controllerで使用する。

To send a hash you include the key name inside the brackets:
<form accept-charset="UTF-8" action="/clients" method="post">
  <input type="text" name="client[name]" value="Acme" />
  <input type="text" name="client[phone]" value="12345" />
  <input type="text" name="client[address][postcode]" value="12345" />
  <input type="text" name="client[address][city]" value="Carrot City" />
</form>
When this form is submitted, the value of params[:client] will be { "name" => "Acme", "phone" => "12345", "address" => { "postcode" => "12345", "city" => "Carrot City" } }. Note the nested hash in params[:client][:address].

Note that the params hash is actually an instance of ActiveSupport::HashWithIndifferentAccess, which acts like a hash but lets you use symbols and strings interchangeably as keys.

このようにnestしたhashをつくれる。また実態はActiveSupport::HashWithIndifferentAccess

4.3 Routing Parameters
The params hash will always contain the :controller and :action keys, but you should use the methods controller_name and action_name instead to access these values. Any other parameters defined by the routing, such as :id will also be available. As an example, consider a listing of clients where the list can show either active or inactive clients. We can add a route which captures the :status parameter in a "pretty" URL:
get '/clients/:status' => 'clients#index', foo: 'bar'
In this case, when a user opens the URL /clients/active, params[:status] will be set to "active". When this route is used, params[:foo] will also be set to "bar" just like it was passed in the query string. In the same way params[:action] will contain "index".

params[:controller]params[:action]が利用できるけど、controller_nameaction_nameを使用するほうがよい。

また:statusのようにrouteでparamsを設定することもできる。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?