0

I want to serialize the newly created resource in this action :

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

But render json: @comment is returning the full object although in my CommentSerializer I have :

class CommentSerializer < ActiveModel::Serializer
  attributes :id
end

I am creating the new resource via 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);
            }
        });

    },

What am I missing here?

Ahmad Al-kheat
  • 1,805
  • 2
  • 16
  • 25

2 Answers2

0

I believe you're missing contentType, so add contentType: "application/json" to your ajax function.

vich
  • 11,836
  • 13
  • 49
  • 66
0

you can explicitly set the serializer when rendering JSON

change

 format.json { render json: @comment }

to

  format.json { render json: CommentSerializer.new(@comment) }
Saiqul Haq
  • 2,287
  • 16
  • 18