ActiveModelSerializer 没有启动

ActiveModelSerializer not kicking in

我想在此操作中序列化新创建的资源:

def create
    @comment = @commentable.comments.build(comment_params)
    @comment.user = current_user
    respond_to do |format|
      if @comment.save
        format.json { render json: @comment }
        format.html { redirect_to @question, notice: "Comment successfully created." }
      else

        format.html { render 'questions/show' }  
      end
    end 
  end

但是 render json: @comment 正在返回完整的对象,尽管在我的 CommentSerializer 中我有:

class CommentSerializer < ActiveModel::Serializer
  attributes :id
end

我正在通过 ajax 创建新资源:

handleSubmit: function(e){
        e.preventDefault();
        $.ajax({
            context: this,
            method: 'POST',
            url: "/questions/" + this.props.question_id + "/comments",
            data: {comment: this.state},
            success: function(data){
                this.props.handleNewComment(data);
                this.setState(this.getInitialState);
            }
        });

    },

我在这里错过了什么?

我认为您缺少 contentType,因此请将 contentType: "application/json" 添加到您的 ajax 函数中。

渲染时可以显式设置序列化器JSON

改变

 format.json { render json: @comment }

  format.json { render json: CommentSerializer.new(@comment) }