0

So in my coffeescript file, I have this HTTP.POST request that essentially calls the create method in my controller to create my object. After this, I want to redirect from the creation page to the edit page. How do I do so.

So imagine there is a button in the view that calls this function in my coffeescript file. This is the relevant code in the coffeescript:

  # Assume data is a hash of parameters that is already provided via form in View.
  $http.post(
    "/apps/feature/role", data  # This should go to controller's create method via ROUTES
    ).then((response) ->
    ??? What do I type here?

This is my create method in the controller:

def create
    @role = ... # creating  role object
    if @role.save
        redirect_to edit_role_path(@role)

Okay so the thing is my view is not being redirected to the edit page role/id/edit, it just stays on the role/new page. Is there something I need to do in my coffeescript after the http call in order to actually redirect it to the edit page?

NOTE: I'm supposed to do it via http calls, so would appreciate some help here! Thanks in advance!

kohrhea
  • 159
  • 7

1 Answers1

0

Since the request is triggered from a javascript application and not a classic form submission, your endpoint should return 2** (201 is ideal) and then you can redirect on the client side using window.location.

alf
  • 18,372
  • 10
  • 61
  • 92
  • Thanks!! But in this case, I would need to get the id of my @roles object after it is being saved, in order to do something like `window.location = "apps/feature/role/" + id + "/edit"`, how can I do so? – kohrhea May 31 '21 at 14:19
  • @kohrhea You can return the id (`@role.id`) in the response or include the path of the new role object in the `Location` HTTP header. Check this similar question: https://stackoverflow.com/q/19199872/512507 – alf May 31 '21 at 20:49