【问题标题】:Active Model Serializer with Namespaced (versioned) Controllers具有命名空间(版本化)控制器的活动模型序列化器
【发布时间】: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。歌曲模型还有一些其他属性,例如 artistcreated_atupdated_at,它们不包含在序列化程序中,因此我的理解是它不会包含在发送到浏览器应用程序的 JSON 中。

我的问题是我的应用程序似乎完全忽略了song_serializer,并且正在发送包含歌曲所有数据库字段的 JSON。欢迎任何意见。

【问题讨论】:

    标签: ruby-on-rails json active-model-serializers rails-api


    【解决方案1】:

    在敲打我的头比我愿意承认的时间更长之后,我的问题似乎在我的歌曲控制器中,就像我渲染 JSON 的方式一样。代替 render json: { song: @song } 我用了 render json: @song 它现在使用我的序列化程序。

    【讨论】:

      猜你喜欢
      • 2016-03-05
      • 2016-10-31
      • 2018-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-30
      • 2015-03-12
      相关资源
      最近更新 更多