JSON return from rails with response_with

I have a jquery ajax call that goes to the create action, and I need to get the answer back as JSON, then to do something with it on the page in the ajax function of success, but for some reason with rails it continues to throw the missing template error :

class MembersController < ApplicationController respond_to :json def create @member = @group.members.build @member.user_id = params[:user_id] respond_with(@member) if @member.save end end 

Should I show nothing at all?

+4
source share
2 answers

If @member.save fails, then the default rendering will be performed, which means that the rails will try to display create.*.erb or create.rjs , etc. You might want to do

 def create @member = @group.members.build @member.user_id = params[:user_id] if @member.save respond_with(@member) else render :nothing => true end end 
+4
source

I believe that you should use

 respond_with(@member) 

Removing conditional.

This will use "Unprocessable Entity" for json requests with an invalid object.

+7
source

Source: https://habr.com/ru/post/1311751/


All Articles