Rails form_with(remote:true)错误

问题描述 投票:0回答:2

我需要一些帮助,

当我尝试使用Rails中的ajax(form_with / remote:true)更新模型时,我收到错误。我能够正常使用XHR请求作为Rails资源的URL(请参阅下面的路由),但是使用自定义URL我收到错误。

controller:

def criar
  @user = current_user
  respond_to do |format|
    if @user.update_attributes(user_params)
      format.js {
        flash[:success] = "Success!"
        redirect_to root_path
      }
    else
      format.js 
    end
  end
end

rspec (request):

put user_criar_path(user), xhr: true,
 :params => { ... }

view:

<%= form_with model: @user, url: user_criar_path(@user), method: :put do |f| %>

routes:

namespace :any do
  namespace :things do
    put '/criar', to: 'user#criar'         # problem with XHR
    put '/atualizar', to: 'user#atualizar' # problem with XHR
  end
end

resources :anything   # this one works fine with XHR

正如你在test.log中看到的那样,Processing by UserController#criar as没有特定的格式(也许这就是问题?)。

test.log:

Processing by UserController#criar as 
  Parameters: { ... }

error message:

Failure/Error:
  respond_to do |format|
    if @user.update_attributes(user_params)
      format.js {
        flash[:success] = "Success!"
        redirect_to root_path
      }
    else
      format.js 
    end

ActionController::UnknownFormat:
ActionController::UnknownFormat

Another request test

it "should be redirect to (criar)" do
  put user_criar_path(1), xhr: true
  expect(response).to redirect_to(new_session_path)
  expect(request.flash_hash.alert).to eq "To continue, please, sign in."
end

Error message

Failure/Error: expect(response).to redirect_to(new_session_path)
  Expected response to be a <3XX: redirect>, but was a <401: Unauthorized>
  Response body: To continue, please, sign in.

观察:

  • 我已经尝试将路线上的网址更改为:put '/criar', to: 'user#criar', constraints: -> (req) { req.xhr? }
  • 正如我之前所说,我使用form_with的XHR对其他资源做同样的事情(测试,控制器)并且它们工作正常。这个与自定义网址无法正常工作。
  • Rails 5.2和Rspec 3.6
  • 任何问题,只需询问评论

提前致谢!

rspec rspec-rails ruby-on-rails-5.2
2个回答
0
投票

尝试在request.xhr?区块之前调用respond_to,正如建议的here


0
投票

Reason of the problem

好吧,经过一番搜索,我找到了答案。

ActionController::UnknownFormat消息相关的问题是由于请求没有很好地定义,因为我们可以在我发布的日志中看到:

由UserController#criar处理

它在句子末尾缺少类型/格式(HTML / JS / ...等)。

The problem was raised by two factors:

  1. 在Rspec上使用rails中的生成路径并将参数传递给它:

user_criar_path(1)put user_criar_path(user), xhr: true, params: {...}

  1. 定义我自己的路线(routes.rb)

get '/user/new', to: 'user#new' # defining my own route

代替

resources: user, only: [:new]#由Rails定义

观察:对于由Rails(资源)定义的路由,将参数传递给generated-path不会引发错误ActionController::UnknownFormat

Solution

从生成的路径中删除参数(对于Rspec和Rails):

put user_criar_path, params: { "user" => { "id" => 1 } }

要么

put user_criar_path, xhr: true, :params => { ... }
© www.soinside.com 2019 - 2024. All rights reserved.