render :new not going to the right place after a validation

前端 未结 2 1135
故里飘歌
故里飘歌 2021-02-18 23:00

I have a \'new\' form that gets validated in a post model. When the validator kicks in, it renders incorrectly.

The new post page path is at \'/posts/new\'

On va

相关标签:
2条回答
  • 2021-02-18 23:03

    If validation fails, user should see the form with the errors and stay at /posts/new. That's what you want, right?

    There's a simple way to achieve this.

    Set remote: true on the form to prevent the url from advancing. Handle ajax:success to replace the form on the page with the newly rendered one.

    $('form[data-remote=true]').on 'ajax:success', (e, data, status, xhr) ->
      if isHTML(data)
        thisForm = "form[id=#{@getAttribute('id')}]"
        $(thisForm).replaceWith $(data).find(thisForm)
    

    isHtml() function is from this question.

    0 讨论(0)
  • 2021-02-18 23:21

    This is the correct behavior from rails.

    In the create action it simply renders the "new" view file. As such the url will be /posts but the view will correctly display the form. There is nothing wrong with this behavior; and in general rails convention is good form. Also the built in rails errors work if you just render new; however if you redirect they won't display.

    If you really feel like you want to go back to that url you need to use:

    redirect_to 
    

    instead of render.

    0 讨论(0)
提交回复
热议问题