Rails 能有人讲解下 response_to |format| 这块吗,一直没弄明白

boyishwei · 2013年11月29日 · 最后由 boyishwei 回复于 2013年11月29日 · 4030 次阅读
respond_to do |format|
  format.html { redirect_to @image, notice: 'Image was successfully created.' }
  format.json { render json: @image, status: :created, location: @image }
  format.js
end

response 如何知道应该按什么 type 来 process?as JS,as HTML? format 是怎么来的,什么将决定 format 的类型?

有点困惑,别见笑。求高手帮我理下....

真想给你编辑下

楼主仔细看看 Rails 默认生成的那些 router,每个 router 的最后一个参数,可以决定它的 format 除此以外,HTTP 里的 Accept 参数也可以决定 format。

标准的 HTTP 是 Accept 参数,但是通常浏览器不会修改 Accept, 所以 Rails 约定俗成的在 URI 后面加上资源格式,比如 ruby-china.org/zgm.html ruby-china.org/zgm.json 对应到你的代码就是

format.html { redirect_to @image, notice: 'Image was successfully created.' }
format.json { render json: @image, status: :created, location: @image }

这样的方式告诉 Rails 怎么处理 Response 的 Content-Type.

四楼说的对

谢谢两位 是的 1、通过 route 里面配置可以 force format 参数 2、通过资源格式可以决定 format 3、在 form 或者 link_to 等控件中加入 remote:true 参数,也会影响 format 参数(as JS)

我现在遇到的问题也就在这个 format 上: 背景:图片上传 Gems

gem 'mini_magick'
gem 'carrierwave'

Route resources :images

在一个 form 中上传图片,提交方式采用 ajax 方式 Form 设定 form_for(@image, remote:true,

代码片段

<div class="field control-group">
  <%= f.label "上传图片", class:"control-label" %>
  <div class="controls">
    <%= f.file_field :instance %>
  </div>
</div>

问题: 如果不选择上传的图片文件,然后提交,跟预期一样,正常。这个时候的 format 是 JS,从以下可知道. Processing by ImagesController#create as JS

但是一旦选择了要上传的图片文件,提交,format 就变成了 HTML, Processing by ImagesController#create as HTML, 也就不能正常调用预期的 create.js.erb。

当然整个 action 正常运作,图片也已上传。

问题就是,我就不知道为什么选了要上传文件后,format 就变了,导致页面不能正常跳转。

#6 楼 @boyishwei 因为 remote form 不支持文件上传,自动退化成普通表单。

respond_to do |format|
        format.html? { redirect_to @image, notice: 'Image was successfully created.' }
        format.json? { render json: @image, status: :created, location: @image }
        format.js? {}
end

这么写也许更好理解些。

#7 楼 @Rei 是这样啊,谢谢了 Rei 再去看看 remote form 为什么不能支持文件上传,,,

curl -H "Content-Type: application/json" -d '{"format":"json"}' 类似这样的

不谢 format 默认是 html

#3 楼 @iBachue people squared 上这两个视频很激励人

需要 登录 后方可回复, 如果你还没有账号请 注册新账号