我正在构建一个带有活动模型序列化器的rails 5API来呈现JSON对象。我在版本中使用命名空间来构造控制器,如下所示。我会展示我的资源来展示一首歌。
application_controller.rb (简化):
class ApplicationController < ActionController::API
include ActionController::Serialization
endsongs_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
endsongs_serializer.rb
class SongSerializer < ActiveModel::Serializer
attributes :id, :title, :band_id
end歌曲模型没有被命名为Api::V1。歌曲模型还有一些其他属性,如artist、created_at和updated_at,这些属性都没有包含在序列化程序中,因此我的理解是,它不会包含在发送给浏览器应用程序的JSON中。
我的问题是,我的应用程序似乎完全忽略了song_serializer,正在发送包含一首歌的所有数据库字段的JSON。欢迎提供任何意见。
发布于 2016-11-27 18:01:00
在我花了很长时间想要承认之后,我的问题似乎在我的songs_controller中,就像我呈现JSON的方式一样。我使用的不是render json: { song: @song },而是render json: @song,现在它使用我的序列化程序。
https://stackoverflow.com/questions/40831887
复制相似问题