I'm using responders gem to dry up my controllers. 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). 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?
2 Answers
Answers 1
I don't think so that it's a problem in responders gem, as I've noticed the same in rails applications. It seems like the default behaviour of rails applications. take a look at this link for the explanation.
Answers 2
I don't think the issue comes from the gem. It just follows RESTFUL API, so does Rails.
That means the path for creating office hours is /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.When we creating unsuccessfully, we need to re-render the error form to users. But we were rendering the form in
createaction. As I said above, the URL for creating is/officehours, so you will see the/officehoursinstead ofofficehours/new
In order to keep the url /officehours/new:
- We can set
/officehours/newinstead of/officehoursfor:createaction. But you should not do that, are we going to breakRESTFUL API? - Creating via
AJAXto 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.
Hope it helps!
0 comments:
Post a Comment