Rails remote =>真正的困惑(没有format.js吗?) [英] Rails remote => true confusion (no format.js?)

查看:88
本文介绍了Rails remote =>真正的困惑(没有format.js吗?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习如何在表单上使用带有remote => true的rails.

I am trying to learn how to use rails with remote => true on forms.

Rails on Rails官方网站上的以下示例使我感到困惑.即使 @ user.save 调用失败时,即使没有" format.js "代码,它也可以正常工作.

The following example on the ruby on rails official website confuses me. It works perfectly even if there is no "format.js" code when the @user.save call fails.

# app/controllers/users_controller.rb
# ......
def create
  @user = User.new(params[:user])

  respond_to do |format|
    if @user.save
      format.html { redirect_to @user, notice: 'User was successfully created.' }
      format.js
      format.json { render json: @user, status: :created, location: @user }
    else
      format.html { render action: "new" }
      format.json { render json: @user.errors, status: :unprocessable_entity }
    end
  end
end

由于js格式不可用,所以我期望出现错误响应.我在这里想念什么?

I was expecting an error response because the js format is not available. What am i missing here?

推荐答案

我找到了我在IRC上寻找的答案.答案来自 https://www.alfajango.com/blog/rails-3-remote-links-and-forms-data-type-with-jquery/:

I found the answer i was looking for on IRC. The answer is from https://www.alfajango.com/blog/rails-3-remote-links-and-forms-data-type-with-jquery/:

较新版本的UJS驱动程序仅保留jQuery的默认设置'/'的dataType.这告诉服务器,把你所拥有的都给我."但是,这会使控制器以第一种格式进行响应恰好在响应者"中列出(请参阅下一部分).因此,如果在format.js之前列出了format.html,应用将响应HTML响应(这意味着它将尝试重定向为POST或DELETE方法AJAX请求).这也不理想.

Newer versions of the UJS driver simply leave jQuery's default dataType of '/'. This tells the server, "Give me whatever you've got." However, this would make the controller respond with the first format that happens to be listed in the Responder (see next section). So if format.html is listed before format.js, the app will respond with the HTML response (which means it will try redirecting for POST or DELETE method AJAX requests). This isn't ideal either.

因此,在最新版本中,我们了解了如何设置默认值,例如它告诉服务器,我更喜欢JS,但无论如何我都会接受您已经拥有了."现在,如果在可用的位置完全定义了format.js响应者格式,将返回JS.如果没有,控制器将然后以列出的第一种格式进行响应.(请参阅讨论主题在这里.)

So in the newest versions, we figured out how to set the default, such that it tells the server, "I'd prefer JS, but I'll take whatever you've got." Now, if format.js is defined at all in the available Responder formats, JS will be returned. If not, the controller will then respond with the first format listed. (See the discussion thread here.)

讨论线程: https://github.com/rails/jquery-ujs/Issues/74

这篇关于Rails remote =>真正的困惑(没有format.js吗?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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