[英]Using responders gem with Rails 5
I'm using responders gem to dry up my controllers. 我正在使用响应者gem来干掉我的控制器。 Here's my current code:
这是我目前的代码:
class OfficehoursController < ApplicationController
def new
@officehour = Officehour.new
end
def create
@officehour = Officehour.create(officehour_params)
respond_with(@officehour, location: officehours_path)
end
def officehour_params
params.require(:officehour).permit(:end, :start, :status)
end
end
The problem that I'm facing right now is: 我现在面临的问题是:
When I send valid parameters to create
, it redirects to officehours/
as expected, however when I get 422 (validation error), it changes the URL from officehours/new
to officehours/
(however it stays at the form page... idk why). 当我发送有效参数进行
create
,它会按预期重定向到officehours/
,但是当我得到422(验证错误)时,它会将officehours/new
更改为officehours/
(但它会保留在表单页面... idk为什么)。 The same happens for edit/update actions. 编辑/更新操作也是如此。
So, I want to stay at the .../new
or .../edit
when I get 422 error, how can I do this? 所以,当我得到422错误时,我想留在
.../new
或.../edit
,我该怎么做?
I don't think the issue comes from the gem. 我不认为问题来自宝石。 It just follows RESTFUL API , so does
Rails
. 它只是遵循RESTFUL API ,
Rails
也是如此。
That means the path for creating office hours
is /officehours
. 这意味着创建
office hours
的路径是/officehours
。 Let's talk about your case: 我们来谈谈你的情况:
There is nothing to say when we creating successfully. 我们成功创建时无话可说。 In your case, you redirect users to
officehours_path
. 在您的情况下,您将用户重定向到
officehours_path
。
When we creating unsuccessfully , we need to re-render the error form to users. 当我们创建失败时 ,我们需要将错误表单重新呈现给用户。 But we were rendering the form in
create
action. 但是我们在
create
动作中渲染表单。 As I said above, the URL for creating is /officehours
, so you will see the /officehours
instead of officehours/new
如上所述,创建的URL是
/officehours
,因此您将看到/officehours
而不是officehours/new
In order to keep the url /officehours/new
: 为了保持url
/officehours/new
:
/officehours/new
instead of /officehours
for :create
action. /officehours/new
而不是/officehours
:create
action。 But you should not do that, are we going to break RESTFUL API
? RESTFUL API
? AJAX
to keep the URL persisted and you have to handle everything, eg: set flash messages on client, using Javascript to redirect in case of success, render the form error in case failure, ... And I don't think the gem help you dry up your application anymore. AJAX
创建以保持URL持久化并且您必须处理所有内容,例如:在客户端设置Flash消息,在成功的情况下使用Javascript重定向,在出现故障时呈现表单错误,...而且我不认为宝石帮助你干掉你的应用程序了。 Hope it helps! 希望能帮助到你!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.