[RUBY] [Rails] How to deal with URL changes after render

Premise

The environment is as follows. Mac OS Catalina 10.15.7 Ruby 2.7.1 Rails 6.0.3.3

I will try to record it as easily as possible, also as a memorandum of my own. To illustrate the problem, we'll use the Rails tutorial as an example.

Specifically, when implementing the user registration function in Chapter 7, the URL will change from / signup to / users when it is rendered on the form screen after registration failure due to validation. The problem, that is

URL changes from localhost: 3000 / signup to localhost: 3000 / users → An error occurs when reloading because the view corresponding to users is not created.

I will explain the solution to the problem.

Cause

When the user registration fails in the create action, render'new' means that the new action is not called and only the view is switched. Since the create action is / users, the URL will naturally be / users after the action. The inconsistency between this URL and the screen is a problem.

Solution policy

The solution is to change the URL with javascript without changing the controller code. Load a specific js only in the target view. (Change from / users to / signup, that is, it looks like the URL is fixed as / signup even after the action.)

Solutions

procedure

  1. Create javascript
  2. Make javascript available in the target view (user registration view)
  3. Embed tags only in the target view

1. Create js file

Create the following js with any directory under app / javascript / packs or any name directly under it (users / signup_render.js in this case).

app/javascript/packs/users/signup_render.js


history.replaceState('', '', '/signup')

I referred to the following. Easy-to-understand explanation about replaceState Learn more about replaceState

I am editing the current history with the history.replaceState () method and replacing / users with / signup with the URL parameters passed to the method.

2. To use js

Create a new compilation setting in ʻapp / javascript / packs / application.js` to compile for the target view.

app/javascript/packs/application.js



//↓ Original code
require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")

//↓ Add this
require("users/signup_render")

The path is described starting from app / javascript.

3. Embed tags in view

Embed javascript_pack_tag in the target view. In the tutorial example, it is the user registration screen shown in Listing 7.20.

erb:app/views/users/new.html.erb



 <!--This is the original code ↓-->

<% provide(:title, 'Sign up') %>
<h1>Sign up</h1>

<div class="row">
  <div class="col-md-6 col-md-offset-3">
    <%= form_with(model: @user, local: true) do |f| %>
      <%= render 'shared/error_messages' %>

      <%= f.label :name %>
      <%= f.text_field :name, class: 'form-control' %>

      <%= f.label :email %>
      <%= f.email_field :email, class: 'form-control' %>

      <%= f.label :password %>
      <%= f.password_field :password, class: 'form-control' %>

      <%= f.label :password_confirmation, "Confirmation" %>
      <%= f.password_field :password_confirmation, class: 'form-control' %>

      <%= f.submit "Create my account", class: "btn btn-primary" %>
    <% end %>
  </div>
</div>

<!--Add this below ↓-->
<% if @user.errors.any? %>
  <%= javascript_pack_tag 'users/signup_render' %>
<% end %>

ʻIf @ user.errors.any?` sets the condition "Validation error occurs = Please process js only when user registration fails and renders."

<% = javascript_pack_tag'users / signup_render'%> means "load ʻapp / javascript / packs / users / signup_render.js`."

I hope you find this helpful.

Other reference pages

-URL changes after Rails5 render'new'[Rails] Reload measures when using render -[About the behavior of the URL after the validation error of the new action and the error that accompanies it](https://ja.stackoverflow.com/questions/36794/new%E3%82%A2%E3%82%AF%E3%82] % B7% E3% 83% A7% E3% 83% B3% E3% 81% AE% E3% 83% 90% E3% 83% AA% E3% 83% 87% E3% 83% BC% E3% 82% B7 % E3% 83% A7% E3% 83% B3% E3% 82% A8% E3% 83% A9% E3% 83% BC% E5% BE% 8C% E3% 81% AEurl% E3% 81% AE% E6 % 8C% 99% E5% 8B% 95% E3% 81% A8% E3% 81% 9D% E3% 82% 8C% E3% 81% AB% E4% BC% B4% E3% 81% 86% E3% 82 % A8% E3% 83% A9% E3% 83% BC% E3% 81% AB% E3% 81% A4% E3% 81% 84% E3% 81% A6) -Handling of Javascript files in Ruby on Rails (Rails 6)

Recommended Posts

[Rails] How to deal with URL changes after render
[Docker + Rails] How to deal with Rails server startup failure
How to get along with Rails
[Introduction to Rails] How to use render
[Android] How to deal with dark themes
[Rails] How to use rails console with docker
How to install Pry after building Rails development environment with Docker
How to deal with Precompiling assets failed.
How to build Rails 6 environment with Docker
[Rails] How to easily implement numbers with pull-down
How to build API with GraphQL and Rails
[Rails] How to build an environment with Docker
How to redirect after user login with Spring-security
How to write Rails
How to uninstall Rails
How to make batch processing with Rails + Heroku configuration
[Rails] How to search by multiple values ​​with LIKE
Diet program with preprocessor (how to deal with i-appli size)
How to push an app developed with Rails to Github
How to deal with fatal: remote origin already exists.
How to delete a new_record object built with Rails
How to deal with No template for interactive request
How to make an almost static page with rails
How to manually generate a JWT with Rails Knock
[Docker environment] How to deal with ActiveSupport :: MessageEncryptor :: InvalidMessage
[How to insert a video in haml with Rails]
How to query Array in jsonb with Rails + postgres
Common problems with WSL and how to deal with them
How to get started with creating a Rails app
How to deal with errors in Rails s could not find a JavaScript runtime.
[rails] How to post images
[Rails] How to use enum
[Rails] How to install devise
[Rails] How to use enum
How to read rails routes
How to use rails join
How to number (number) with html.erb
How to update with activerecord-import
How to terminate rails server
How to write Rails validation
How to write Rails seed
[Rails] How to use validation
[Rails] How to disable turbolinks
[Rails] How to use authenticate_user!
[Rails] How to use "kaminari"
[Rails] How to implement scraping
[Rails] How to make seed
How to write Rails routing
[Rails] How to install simple_calendar
[Rails] How to install reCAPTCHA
[Rails] How to use Scope
How to automatically generate ER diagram when migrating with Rails6
How to set environment variables when using Payjp with Rails
[Rails] Differences between redirect_to and render methods and how to output render methods
[With back tricks] How to introduce React to the simplest Rails
How to specify db when creating an app with rails
How to build Rails, Postgres, ElasticSearch development environment with Docker
How to deal with the error ERROR: While executing gem ... (Gem :: FilePermissionError)
How to deal with Bundler :: Dsl :: DSLError by rewriting gemfile
How to erase test image after running Rspec test with CarrierWave
How to deal with different versions of rbenv and Ruby