0
0

More than 1 year has passed since last update.

【rails】ストロングパラメータでmergeメソッドを使う

Posted at

RealWorldでエンドポイントを作る

RealWorld という OSS のプロジェクトがある。
RealWorld は実世界と同じ機能を持つプラットフォームを作ることで、学習したいフレームワークの技術を習得することを目的としたプロジェクトのこと。

RealWorld

詳細はリンク先をご覧いただきたいが、
エンドポイントの作成で、次のようなJSONデータを指定URLにPOSTした場合、

POST /api/articles

{
  "article": {
    "title": "How to train your dragon",
    "description": "Ever wonder how?",
    "body": "You have to believe"
  }
}

次のようなJSONデータを返すコードを作成するよう指示されている。

{
  "article": {
    "slug": "how-to-train-your-dragon",
    "title": "How to train your dragon",
    "description": "Ever wonder how?",
    "body": "It takes a Jacobian",
    "createdAt": "2016-02-18T03:22:56.637Z",
    "updatedAt": "2016-02-18T03:48:35.824Z"
  }
}

"slug"はPOSTするJSONデータにはないため、リクエストを受けたら"slug"の値を作成し、"slug"をマージしてデータを返すようコードを書かなければならない。

どうしたか?

そこでmergeメソッドを使って、次のコードを作成してみた。

params.require(:article).permit(:title, :description, :body).merge(slug: params['article']['title'].gsub(' ', '-'))

params['article']['title'] で取得した値(ここで言う、"title": "How to train your dragon" の部分)を置換したものをレコードにマージしている。

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