In Rails when a resource create action fails and calls render :new, why must the URL change to the resource's index url?

后端 未结 5 1790
死守一世寂寞
死守一世寂寞 2020-12-07 14:40

I have a resource called Books. It\'s listed as a resource properly in my routes file.

I have a new action, which gives the new view the standard:

@         


        
5条回答
  •  情歌与酒
    2020-12-07 15:31

    Just had the very same question, so maybe this might help somebody someday. You basically have to make 3 adjustments in order for this thing to work, although my solution is still not ideal.

    1) In the create action:

    if @book.save
      redirect_to(@book)
    else
      flash[:book] = @book
      redirect_to new_book_path
    end
    

    2) In the new action:

    @book = flash[:book] ? Book.new(flash[:book]): Book.new
    

    3) Wherever you parse the flash hash, be sure to filter out flash[:book].

    --> correct URL is displayed, Form data is preserved. Still, I somehow don't like putting the user object into the flash hash, I don't think that's it's purpose. Does anyboy know a better place to put it in?

提交回复
热议问题