0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Railsにおけるparamsの二つの使い方。

Posted at

1 URLから値を取得する

前提条件

ルーティング

Rails.application.routes.draw do
  get 'users/:id', to: 'users#show'
end

コントローラー

class UsersController < ApplicationController
  def show
    @user = User.find(params[:id]) 
  end
end

URL: xxx/users/1 にアクセス
### 結果
URLの1の部分がparams 内の:idという変数に入れられる。

params = {
  controller: 'users',
  action: 'show', 
  id: '1',         
}

prams[:id] = "5"になる
余談だが最後にuserオブジェクトに代入すると、userテーブルの値が取得できる。

@user.id          # => 3
@user.name        # => "田中"
@user.email       # => "tanaka@example.com"

2 フォームから入力内容を受け取るname=xxで受け取る

以下のような、タイトルとコンテンツを入れる入力欄があったとする。

<form action="/posts" method="post">
  <input type="text" name="title">
  <textarea name="content"></textarea>
  <button type="submit">送信</button>
</form>

コントローラ

class PostsController < ApplicationController
  def create
    # フォーム送信時、params[:title]とparams[:content]に
    # 入力された値が入る
    @post = Post.new(
      title: params[:title],
      content: params[:content]
    )
  end
    
end

結果

paramsには以下が入る。

params = {
  "controller" => "posts",
  "action" => "create",
  "title" => "xxxxx",           # フォームのtitle入力値
  "content" => "yyyyy", # フォームのcontent入力値
}

params[:title]
params[:content]
で取得可能になる。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?