【问题标题】:ActiveModelSerializer not kicking inActiveModelSerializer 没有启动
【发布时间】:2016-09-18 13:29:14
【问题描述】:

我想在这个动作中序列化新创建的资源:

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);
            }
        });

    },

我在这里缺少什么?

【问题讨论】:

    标签: ruby-on-rails ajax ruby-on-rails-4 active-model-serializers react-rails


    【解决方案1】:

    您可以在呈现 JSON 时显式设置序列化程序

    改变

     format.json { render json: @comment }
    

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 请求发送正常,响应没有被序列化,所以不是这个原因。
      猜你喜欢
      • 1970-01-01
      • 2011-12-09
      • 1970-01-01
      • 2021-05-06
      • 1970-01-01
      • 2014-11-23
      • 2016-07-20
      • 2021-12-10
      • 2016-12-19
      相关资源
      最近更新 更多