我需要一些帮助,
当我尝试使用Rails中的ajax(form_with / remote:true)更新模型时,我收到错误。我能够正常使用XHR请求作为Rails资源的URL(请参阅下面的路由),但是使用自定义URL我收到错误。
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
put user_criar_path(user), xhr: true,
:params => { ... }
<%= form_with model: @user, url: user_criar_path(@user), method: :put do |f| %>
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
没有特定的格式(也许这就是问题?)。
Processing by UserController#criar as
Parameters: { ... }
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
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
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对其他资源做同样的事情(测试,控制器)并且它们工作正常。这个与自定义网址无法正常工作。提前致谢!
尝试在request.xhr?
区块之前调用respond_to
,正如建议的here
好吧,经过一番搜索,我找到了答案。
与ActionController::UnknownFormat
消息相关的问题是由于请求没有很好地定义,因为我们可以在我发布的日志中看到:
由UserController#criar处理
它在句子末尾缺少类型/格式(HTML / JS / ...等)。
user_criar_path(1)
或put user_criar_path(user), xhr: true, params: {...}
get '/user/new', to: 'user#new' # defining my own route
代替
resources: user, only: [:new]
#由Rails定义
观察:对于由Rails(资源)定义的路由,将参数传递给generated-path不会引发错误ActionController::UnknownFormat
。
从生成的路径中删除参数(对于Rspec和Rails):
put user_criar_path, params: { "user" => { "id" => 1 } }
要么
put user_criar_path, xhr: true, :params => { ... }