问题
I have a subscriber#create method that is only used for ajax submits to it (the html form uses data-remote="true" to do the Ajax. The form does indeed submit and the data ends up in the db but the method throws an error saying that the template was not found.
How can I specify a function as being an Ajax handler in Rails? -- one that doesn't have to render a template, etc.
Here is what the method looks like:
class SubscribersController < ApplicationController
def create
Subscriber.create(:email => params[:email],
:ip_address => request.remote_ip,
:referring_page => request.referer ) unless Subscriber.find_by_email(params[:email])
end
end
回答1:
You should handle the call in your respond_to properly.
...
respond_to do |format|
format.html
format.js { :nothing => true }
end
The thing it, you should probably return something. Even if it is an AJAX call, you should send something back to let the caller know that the creation was a success.
def create
@subscriber = Subscriber.new(#your params)
respond_to do |format|
if @subscriber.save
format.js { render :json => @subscriber, :status => :created, :location => @susbscriber }
else
format.js { render :json => @susbcriber.errors, :status => :unprocessable_entity }
end
end
end
Also, you shouldn't have to do the unless Subscriber.find_by_email(params[:email]) in your controller. You should just add validates_uniqueness_of :email to the Subscriber model.
回答2:
you want something like render :layout => !request.xhr? in your controller, this will prevent the layout if the request is ajax
来源:https://stackoverflow.com/questions/8196666/rails-method-that-handles-ajax-complaining-about-no-template