ActiveModelSerializer没有踢

时间:2016-09-18 13:29:14

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

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

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

    },

我在这里缺少什么?

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

您可以在渲染JSON时显式设置序列化程序

变化

 format.json { render json: @comment }

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