jQuery post to Rails

You can setup your post to structure the data in any way as long as it is interpreted correctly on the rails end, but best practice is to have an object of ‘model-name’ with all the values.

Javascript

$.ajax({
    url: "/sub_comments",
    type: "POST",
    data: {subcomment: {
             field: val, 
             field2: val, etc... }},
    success: function(resp){ }
});

Rails

def create
  @sub_comment = SubComment.new params['subcomment']
  if @sub_comment.save
    render :json => { } # send back any data if necessary
  else
    render :json => { }, :status => 500
  end
end

Leave a Comment