LoginSignup
10
9

More than 5 years have passed since last update.

jbuilder has_manyオブジェクトの属性の展開を制限する

Last updated at Posted at 2014-07-04

jbuilderを利用して、has_manyをもつオブジェクトをjson化にする際に、単純にextractを行うと、全ての属性が展開されます。以下のようにすると、指定した属性のみを展開できます。

json.(@customer, :id, name)
json.scores(@customer.scores, :game_id, :score) 

上記は下記のようなjsonを生成します。json.scoresのメソッド名を
変更するとjsonの属性名も変わります。

{
  "id":2,
  "name":"123456789012",
  "scores":
  [
    {
      "game_id":1,
      "score":256
    },
    {
      "game_id":2,
      "score":0
    }
  ]
}
class Customer < ActiveRecord::Base
  has_many :scores
end

class Score < ActiveRecord::Base
 belong_to :customer
end

こちらに色々なJbuilderでのJSON生成例をまとめてみました。http://qiita.com/hmu29/items/c4e365cc0a9d465731f8

10
9
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
10
9