I'm aware POST requests aren't meant for navigation but I just want to check if what I've been tasked with is possible.
I have a page in my Rails app - let's call it cars#index. I'm required to make a selection of cars on this page, then submit the selection and be taken to a new page for car_sales, with my selection listed in another table.
I have a table which I can make a selection of cars, and then want to POST this data, rendering a new page at car_sales#new - with a list of my previously selected cars.
Is this even possible?
# POST car_sales#new
def new
@cars = Car.where(id: selected_car_id_params)
respond_to do |format|
format.html
end
end
Normally, you would POST to a create action, which would then redirect to some other page which would query your cars which were persisted in the database. The difference here is I don't want to persist in the DB yet.
I've got as far as POSTing the data from my cars#index page, except what's returned in the network tab is the HTML for the car_sales#new page - i.e. the browser stays on the same page but it doesn't redirect.
Can someone provide a technical reason why this happens?
Here's my index method though don't think it's relevant here:-
# GET cars#index
def index
@cars = Car.all
end
This is fairly easy to acheive by just adding an additional POST route.
However it really just begs the question "But why?". You don't need to use
POSTfor a form submission that's idempotent. You can just use the standard GET route.There is nothing forcing you to persist anything in response to a form submission. That is just convention. Nor do you actually need to persist anything as what you want to do is simply render the view with additional inputs.
Parameters can also be forwarded either through the query string or the session - if you actually need it (you don't).
You're expecting the wrong thing. A form submission doesn't cause a redirect. It's a GET/POST request to the server and the server can respond to it however it wants.
In your case the controller is implicitly rendering a view in response and sending the default
200 - OKstatus code. If you actually wanted a redirect (you don't) the server needs to respond with a3XXstatus code and a location header which you do withredirect_to.As to why the client isn't rendering the new view than I can only guess that the request is being sent as a XHR request or that you're not actually sending the correct request or rendering what you think you are.