はじめに
JBuilderのシンタックスになんともしっくりこないので、簡単なrender jsonでなんとかしていました。
render json: { hoge: @hoge }, status: 200
or
render json: @hoge, status: :ok
でも、複雑なjsonを整形する必要が出てくると、as_jsonなどを使ってmodel側で指定したり、controller内で整形用のメソッドを用意したりと、コードが見づらくなってしまいました。
JBuilderを使えば、いい感じに収まりがつきましたが、どうもシンタックスが嫌でした。
そこで ActiveModelSerializersを使うことにしました。
ActiveModelSerializer
概要
app/serializers/以下にjsonの整形を担当するコードを書いていきます。
JBuilderの様な特別なDSLを使うことはなく、Railsのコードでよく見る書き方を用いて書けます。
Install
Gemfile
gem 'active_model_serializers'
Usage
$ rails g serializer hoge(model_name)
app/serializers/hoge_serializer.rb
class HogeSerializer < ActiveModel::Serializer
# write attributes you want to render of the Model
attributes :profile, :updated_time, :url, :stadium_address, :tel
# write association you want to use in this rendering json
has_many :friends
# delegation code
delegate :current_user, :to => :scope
# Configuration of each attributes
def profile
"#{object.name} #{object.address}"
end
def updated_time
object.updated_time.to_i
end
def url
"http://www.nfl.com/#{obje.ctcity}"
end
def players
object.players.collect { |player| [player.name, player.number, player.age]}
end
def tel
if current_user.is_admin?
{:tel_num => object.tel_num, :available => object.avaliable_range, :costs => object.costs}
else
{}
end
end
end
configuration of output of association
make a serializer of the model. and write config code.
$ rails g serializer friends
app/serializers/friend_serializer.rb
class HogeSerializer < ActiveModel::Serializer
attributes :name, :photo
end
Controller
hoge_controller.rb
~~
def show
~~
render json: @hoge, status: :ok
end
if you want to use various serializer at a controller...
render json: @hoge, status: :ok, serializer: HogeSerializer
One More Thing
指定するステータスコードは、例えば200でも:okでもいいかと思いますが、どちらにしても全部把握しておいたほうがいいので、以下をチェック。
References
- ActiveModelSerializers
- ActiveRecord::Serialization