ruby-on-rails - 当响应不断以 JSON 格式返回时,如何重定向到页面?

标签 ruby-on-rails ruby json ruby-on-rails-4

我正在使用 dropzone.js用于图片上传。

在我的 coffeescript js 文件中,我有 dropzone 的设置:

Dropzone.autoDiscover = false

dropzone = new Dropzone('#item-form',
  maxFiles: 1
  maxFilesize: 1
  paramName: 'item[image]'
  headers: "X-CSRF-Token" : $('meta[name="csrf-token"]').attr('content')
  addRemoveLinks: true
  clickable: '#image-preview'
  previewsContainer: '#image-preview'
  thumbnailWidth: 200
  thumbnailHeight: 200
  parallelUploads: 100;
  autoProcessQueue: false
  uploadMultiple: false)

$('#item-submit').click (e) ->
  e.preventDefault()
  e.stopPropagation()
  if dropzone.getQueuedFiles().length > 0
    dropzone.processQueue()
  else
    $('#item-form').submit()
  return
return

除了选项之外,单击我的表单上的提交按钮,如果存在图像,将处理该图像,如果没有图像,则无论如何都会提交表单。

接下来是我的 Controller (相关代码):

  def create
    @item = current_user.items.build(item_params)

    respond_to do |format|
      if @item.save
        format.html { redirect_to @item, notice: 'Item was successfully created.' }
        format.json { render :show, status: :created, location: @item }
      else
        format.html { render :new }
        format.json { render json: @item.errors, status: :unprocessable_entity }
      end
    end
  end

比我的表格:

= form_for @item, html: {id: 'item-form', class: 'form', multipart: true} do |f|
 = f.text_field :name, class: 'form-control'

    %main#image-preview
     Add a Photo
     .fallback
      = f.file_field :image, multiple: false

= f.submit 'Done', id: 'item-submit'

所以现在这个设置一切正常。在我收到 Missing Template 错误之前,因为我需要创建一个 show.json.erb 模板,在我这样做之后,它在日志中给了我这个:

Started POST "/items" for 127.0.0.1 at 2015-10-16 21:36:18 -0700
Processing by ItemsController#create as JSON
...................
   (10.7ms)  COMMIT
  Item Store (142.4ms)  {"id":12}
  Rendered items/show.json.erb (0.4ms)
Completed 201 Created in 2759ms (Views: 6.1ms | Searchkick: 142.4ms | ActiveRecord: 11.9ms)

所以现在我想知道什么时候使用 JSON 或者只是在这种情况下一起使用,如果它一直强制我使用 JSON,我该如何重定向到项目显示页面?

UPDATE

保存项目时更改我的响应时:

if @item.save
  format.html { redirect_to @item }
  format.json { redirect_to @item }
else

它这样做:

Started GET "/items/13" for 127.0.0.1 at 2015-10-16 22:54:29 -0700
Processing by ItemsController#show as JSON
  Parameters: {"id"=>"13"}
  User Load (0.4ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1  ORDER BY "users"."id" ASC LIMIT 1  [["id", 2]]
  Item Load (0.4ms)  SELECT  "items".* FROM "items" WHERE "items"."id" = $1 LIMIT 1  [["id", 13]]
  User Load (0.3ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1  [["id", 2]]
  Rendered items/show.json.erb (0.7ms)
Completed 200 OK in 137ms (Views: 7.5ms | ActiveRecord: 25.2ms)

所以我相信一些我必须如何以 HTML 形式执行 GET 请求才能正确执行?

UPDATE 2

我在下面做了以下操作,还必须创建一个 create.json.erb 文件。

if @item.save
  format.html { redirect_to @item }
  format.json { redirect_to item_path(@item, format: :html) } and return
else

Started POST "/items" for 127.0.0.1 at 2015-10-16 23:36:13 -0700
Processing by ItemsController#create as JSON............

   (12.9ms)  COMMIT
  Item Store (426.1ms)  {"id":18}
  Rendered items/create.json.erb (19.6ms)
Completed 200 OK in 3892ms.....

它仍然没有重定向我,给我与以前相同的结果。

UPDATE 3

这样做 format.json { redirect_to item_path(@item) and return} 不会重定向到显示页面,而是在 JSON 中处理。做 format.json { redirect_to item_path(@item, format: :html) and return} 给我留下了 Started GET "/items/19.html 这是错误的因为您无法获得末尾带有 .html 的页面。

UPDATE 3

仍然没有任何变化的运气:

format.json {render :show, status: :created, location: item_url(@item, format: :html )}

我想我必须使用 window.location 进行重定向,它是 JavaScript 的一部分,在我的代码中的某个地方,但需要做更多的研究。我不在乎是否可以使用 jshtml 格式,只要它能工作。

UPDATE 4

好的,所以我能够在我的 GitHub 上的全新测试应用程序中获得相同的行为:https://github.com/justintech/dropzonetest .这会抛出 来自服务器的无效 JSON 响应。 所以我猜我的真实应用程序做同样的事情,但它只是出现故障并作为完整响应传递。诡异的。请随时查看。

最佳答案

如果您希望两种格式响应相同,请忘记格式部分。您所需要的只是重定向。试试 redirect_to(@item)

编辑:

我看了你的代码。我发现以下工作:

items_controller.rb:

def create
  @item = Item.new(item_params)

  respond_to do |format|
    if @item.save
      format.html { redirect_to @item, notice: 'Item was successfully created.' }
      format.json { render json: @item }
    else
      format.html { render :new }
      format.json { render json: @item.errors, status: :unprocessable_entity }
    end
  end
end

在 items.coffee 中:

$(document).ready ->
  # disable auto discover
  Dropzone.autoDiscover = false

  dropzone = new Dropzone('#item-form',
    maxFiles: 1
    maxFilesize: 1
    paramName: 'item[image]'
    headers: "X-CSRF-Token" : $('meta[name="csrf-token"]').attr('content')
    addRemoveLinks: true
    clickable: '#image-preview'
    previewsContainer: '#image-preview'
    thumbnailWidth: 200
    thumbnailHeight: 200
    parallelUploads: 100;
    autoProcessQueue: false
    uploadMultiple: false)

  $('#item-submit').click (e) ->
    e.preventDefault()
    e.stopPropagation()
    if dropzone.getQueuedFiles().length > 0
      dropzone.processQueue()
    else
      $('#item-form').submit()

  dropzone.on 'success', (file, responseText) ->
    window.location.href = '/items/' + responseText.id

关于ruby-on-rails - 当响应不断以 JSON 格式返回时,如何重定向到页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33182825/

相关文章:

mysql - 使用 MySQL 或 Rails 计算计划结束与下一个开始之间的差异

ruby-on-rails - 如何设置存储单元的yml文件格式 `number_to_human_size`

ruby-on-rails - 如果记录存在,Rails 如何改进?

java - Rail 的 'Gotchas' 和学习曲线 - 它会停止吗?

java - Android,Json解析错误

javascript - 使用 angularJS 从 JSON url 获取数据

sql - Oracle JSON_EQUAL 条件的 T-SQL 等价物是什么?

ruby-on-rails - 如何在 Ruby on Rails 上嵌入带有 ActionText/Trix 的 iframe?

ruby-on-rails - 新手问题,这里的 'yield'是什么意思?

ruby - "monkey-patch"Ruby 的基类有更好的方法吗?