Rails method that handles ajax complaining about no template?

自作多情 提交于 2019-12-11 09:55:33

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!