处理 ajax 抱怨没有模板的 Rails 方法? [英] Rails method that handles ajax complaining about no template?

查看:30
本文介绍了处理 ajax 抱怨没有模板的 Rails 方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 subscriber#create 方法,它只用于 ajax 提交给它(html 表单使用 data-remote="true" 来做 Ajax.表单确实提交,数据最终在数据库中,但该方法抛出一个错误,指出找不到模板.

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.

如何将函数指定为 Rails 中的 Ajax 处理程序? -- 一个不必呈现模板等的函数.

How can I specify a function as being an Ajax handler in Rails? -- one that doesn't have to render a template, etc.

方法如下:

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

推荐答案

你应该正确处理你的 respond_to 中的调用.

You should handle the call in your respond_to properly.

...
respond_to do |format|
  format.html 
  format.js   { :nothing => true }
end

那个东西,你应该返回东西.即使是 AJAX 调用,也应该回送一些东西让调用者知道创建成功.

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

此外,您不必在控制器中执行unless Subscriber.find_by_email(params[:email]).您应该将 validates_uniqueness_of :email 添加到订阅者模型.

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.

这篇关于处理 ajax 抱怨没有模板的 Rails 方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆