Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using responders gem with Rails 5

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?

like image 202
dev_054 Avatar asked Mar 26 '18 01:03

dev_054


1 Answers

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 create action. As I said above, the URL for creating is /officehours, so you will see the /officehours instead of officehours/new


In order to keep the url /officehours/new:

  • We can set /officehours/new instead of /officehours for :create action. But you should not do that, are we going to break RESTFUL API?
  • Creating via 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.

Hope it helps!

like image 162
fongfan999 Avatar answered Nov 08 '22 04:11

fongfan999