【发布时间】:2016-11-27 17:40:26
【问题描述】:
我正在构建一个带有活动模型序列化程序的 rails 5 api 来呈现 JSON 对象。我使用命名空间为版本构建了我的控制器,如下所示。我将展示我的一个资源来展示一首歌曲。
application_controller.rb(简化版):
class ApplicationController < ActionController::API
include ActionController::Serialization
end
songs_controller.rb:
class Api::V1::SongsController < ApplicationController
before_action :set_song, only: [:show, :update, :destroy]
def show
authorize @song
render json: { song: @song }
end
private
def song_params
params.require(:song).permit(:title, :artist, :band_id)
end
def set_song
@song = Song.find(params[:id])
end
end
songs_serializer.rb
class SongSerializer < ActiveModel::Serializer
attributes :id, :title, :band_id
end
歌曲模型未命名为Api::V1。歌曲模型还有一些其他属性,例如 artist、created_at 和 updated_at,它们不包含在序列化程序中,因此我的理解是它不会包含在发送到浏览器应用程序的 JSON 中。
我的问题是我的应用程序似乎完全忽略了song_serializer,并且正在发送包含歌曲所有数据库字段的 JSON。欢迎任何意见。
【问题讨论】:
标签: ruby-on-rails json active-model-serializers rails-api