2015年6月8日月曜日

ActiveRecordにattr_accessorで定義したものがto_jsonで含まれない

何も考えずにActiveRecordでto_jsonやっていたら、
attr_accessorで定義したものがJSONに含まれてなかったので、
そのときに調べたことを書いていきます。

クラスはこんな感じ
# == Schema Information
#
# Table name: items
#
#  id         :integer          not null, primary key
#  name       :string
#  img        :string
#  price      :integer
#  created_at :datetime         not null
#  updated_at :datetime         not null
#
 
class Item < ActiveRecord::Base
  attr_accessor :view_img_url
end

item = Item.new
item.name = 'なまえ'
item.img = 'test.jpg'
item.view_img_url = 'http://aaa.bbb/ccc/ddd/test.jpg'
item.price = 100
 
p item.to_json
JSONにview_img_urlが含まれていませんでした。
view_img_urlを含むためにはto_jsonの引数にmethods: :view_img_urlを与える必要があります。
p item.to_json(methods: :view_img_url)
これでJSONにview_img_urlが含まれるようになりました。

0 件のコメント:

コメントを投稿