我在这里需要帮助
当我尝试使用来自Rails的ajax更新模型时出现错误(form_with / remote:true)。我能够很好地处理XHR请求的URL,这些URL是Rails的资源(请参见下面的路由),但是使用自定义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对其他资源执行相同的操作(测试,控制器),并且它们工作正常。这个带有自定义网址的网址无效。谢谢!
答案 0 :(得分:0)
根据建议尝试在request.xhr?
块之前调用respond_to
here
答案 1 :(得分:0)
好吧,经过一番搜索,我找到了答案。
与ActionController::UnknownFormat
消息相关的问题是由于请求的定义不正确,正如我们在日志中看到的那样:
通过UserController#criar作为
进行处理
句子结尾缺少类型/格式(HTML / JS / ... etc)。
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(资源)定义的路由,将参数传递到生成路径不会引发错误ActionController::UnknownFormat
。
从生成路径中删除参数(对于Rspec和Rails而言):
put user_criar_path, params: { "user" => { "id" => 1 } }
或
put user_criar_path, xhr: true, :params => { ... }