I’ve been reading a lot of posts about how Rails handles remote: true
, but I still fail to understand why this is happening. One of my form is a remote form, which looks like this:
<%= form_with model: @transfer, scope: :transfer, url: transfers_path, method: 'post', remote: true do |f| %>
And in my create
action, I just have this:
def create @transfer = @account.transfers.build(transfer_params) respond_to do |format| if @transfer.valid? format.html { redirect_to pending_transactions_path } else flash.now[:error] = "An error occurred" format.js end end end
The create.js.erb
template is strictly used to handle when there’s an error saving the @transfer
and I also tried to empty it out with no code. And for some reason, when I submit this form, it did redirected me to to the pending_transactions_path
.
However, in another part of my code, I have an ajax request like this:
$ .ajax({ method: "GET", url: "/handle_timeout" });
And my controller action looks like this:
def handle_timeout respond_to do |format| format.html { redirect_to pending_transactions_path } end end
And it’s not redirecting for some reason. In my Rails log, I can see that it’s redirecting:
10:19:18 web.1 | Redirected to http://localhost:3000/transactions/pending 10:19:18 web.1 | Completed 302 Found in 67ms (ActiveRecord: 50.6ms) 10:19:18 web.1 | Started GET "/transactions/pending" for ::1 at 2019-05-31 10:19:18 -0700 10:19:18 web.1 | Processing by TransactionsController#pending_transfers as */*
I had to follow another SO answer to get it to redirect. Link to that answer: https://stackoverflow.com/a/17689223/3504731
Am I wrong to think remote: true
is the same as making an $ .ajax
request? Why does my page redirect when I submit the first form, but doesn’t redirect when the second ajax request is ran? Does Rails’ remote: true
do more magic under the hood versus an ajax request?
I am running Rails 5.2.1. Any insights on this would be greatly appreciated. Thank you for reading!