LoginSignup
108
114

More than 5 years have passed since last update.

Rails Jbuilderの使い方

Posted at

railsのコンソールにてJbuilderの使い方を確認してみました。

例とするモデル

class Customer < ActiveRecord::Base
# name,email,password,country
end

単一要素

全属性を出力


customer = Customer.find(1)
Jbuilder.encode do |json|
  json.my_customer customer
end

メソッド名がJSONの属性名になる。

{
  "my_customer": {
    "name": "A C",
    "email": ~~~~~~,
    (他の要素)
  }
}

特定の属性を出力する場合

customer = Customer.find(1)
Jbuilder.encode do |json|
  json.my_customer customer, :email
end
{
  "my_customer": {
    "email": "a@b"
  }
}

配列要素を出力する場合

全属性


customers = Customer.where(id: [1,2])

Jbuilder.encode do |json|
  json.my_customers customers
end

{
  "my_customers": [{
    "name": "A C",
    "email": ~~~~~~,
    (他の要素)
  },{
    "name": "A B",
    "email": ~~~~~~,
    (他の要素)
  }]
}  

属性指定

customers = Customer.where(id: [1,2])

Jbuilder.encode do |json|
  json.my_customers customers, :email
end
{
  "my_customers": [{
    "email": ~~~~~~,
  },{
    "email": ~~~~~~,
  }]
}  

ハッシュの中にオブジェクトを含む場合

全属性

obj = {
  rank: 1,
  customer: Customer.find(1)
}

Jbuilder.encode do |json|
  json.my_customer obj
end
{ "my_customer": {
    "rank": 1,
    "customer": {
      "name": "A B",
      "email": ~~~~~~,
      (他の要素)  
    }
  }
}

属性を指定する場合

obj = {
  rank: 1,
  customer: Customer.find(1)
}

Jbuilder.encode do |json|
  json.my_customer do
    json.rank obj[:rank]
    json.customer obj[:customer], :email
  end
end
{ "my_customer": {
    "rank": 1,
    "customer": {
      "email": ~~~~~~
    }
  }
}

ハッシュが配列の要素の場合

属性名なしの配列を生成する場合

objs = [ {
    rank: 1,
    customer: Customer.find(1)
  }, {
    rank: 2,
    customer: Customer.find(2)
  }
]

Jbuilder.encode do |json|
  json.array! objs do |obj|
    json.rank obj[:rank]
    json.customer obj[:customer], :email
  end
end
[{
  "rank": 1,
  "customer": {
    "email": ~~~~~~
 },{
  "rank": 2,
  "customer": {
    "email": ~~~~~~
 }
}]

属性名有りの配列を生成する場合

objs = [ {
    rank: 1,
    customer: Customer.find(1)
  }, {
    rank: 2,
    customer: Customer.find(2)
  }
]

Jbuilder.encode do |json|
  json.ranking do
    json.array! objs do |obj|
      json.rank obj[:rank]
      json.customer obj[:customer], :email
    end
  end
end

参考

108
114
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
108
114