43
41

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 JBuilder 入れ子・配列・部分テンプレートのサンプル

Last updated at Posted at 2015-02-21

出力したいJSON

入れ子構造と配列を組み合わせた JSON を出力しています。

{
  "companies": [
  {
    "id": 1,
    "name": "Nintendo",
    "staffs": [
    {
      "id": 1,
      "name": "Iwataさん"
    }
    ]
  },
  {
    "id": 2,
    "name": "Google",
    "staffs": [ ]
  }
  ]
}

ソースコード

json.jbuilder ファイル

app/views/companies/index.json.jbuilder
# companies.json にアクセスすると、このjbuilderが呼ばれる

# json.キー名 do ~ end を使うと、
# 入れ子構造を作ることができる
json.companies do
  # json.array!(配列) do |要素名| end を使うと、
  # 配列構造を作ることができる
  json.array!(@companies) do |company|
    # json.partial! モデル変数 を使うと、
    # 部分テンプレートを表示する
    json.partial!(company)
  end
end
app/views/companies/_company.json.jbuilder
# 部分テンプレート(会社)

# company 変数は、
# 部分テンプレートの呼び出し元で渡された引数。
json.id(company.id)
json.name(company.name)
# 入れ子構造を作る
json.staffs do
  # 配列構造を作る
  json.array!(company.staffs) do |staff|
    # 従業員の部分テンプレートを表示
    json.partial!(staff)
  end
end
app/views/staffs/_staff.json.jbuilder
# 部分テンプレート(従業員)

# staff 変数は、
# 部分テンプレートの呼び出し元で渡された引数。
json.id(staff.id)
json.name(staff.name + 'さん')

Controller

scaffold で生成したものをそのまま使っています。

sccafold.sh
rails g scaffold company name:string
rails g scaffold staff name:string

Model

app/models/company.rb
class Company < ActiveRecord::Base
  has_many :staffs
end
app/models/staff.rb
class Staff < ActiveRecord::Base
  belongs_to :company
end
43
41
1

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
43
41

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?