I've been looking for similar topics but although I've read a lot I'm still a bit confused about the respond_to block usage.
I'm doing an AJAX request by using form_with in the client side. In the controller, my action looks like this:
def create
@role = Role.new(role_params)
respond_to do |format|
if @role.save
format.html { redirect_to url_for(controller: 'roles', action: 'index') }
format.json { render json: { :location => url_for(controller: 'roles', action: 'index') }, status: 302 }
else
format.html { render action: 'new' }
format.json { render json: { :errors => @role.errors }, status: 422 }
end
end
end
The way I understand respond_to bock is that when you make an AJAX request it should answer back by using json, and If you make a regular request it should answer back by using html. Is that correct?
In this case, it always answers back by using format.html. I've checked that If I put format.json first (above format.html) It indeed answer back by using json.
What's wrong or what am I missing?
Thanks!
admin_roles_path(format: :json)for html try:admin_roles_path(format: :html)does this work for you ?