Ruby on Rails: How would i stay on the same page if the post is not saved?

前端 未结 3 785
小鲜肉
小鲜肉 2021-02-19 03:59
def create
    @addpost = Post.new params[:data]
    if @addpost.save
        flash[:notice] = \"Post has been saved successfully.\"
        redirect_to posts_path
    e         


        
3条回答
  •  梦谈多话
    2021-02-19 04:22

    Hey this answer is super late but thought I'd add it for anyone that comes across it. Probably the most simple solution for what you want to achieve is to add required: true to all of the form inputs you want filled out. E.g

    f.text_field :title, required: true, class: "whateverclassyouwant" 
    

    This way the form will ONLY be submitted if these fields have been filled in correctly and if not an error flash message will pop up on the field that it needs to be completed. The default flash messages that pop up can be custom styled also, Google how to do so.

    This way you can remove the else redirect all together in your create method as it will never get to that point, and just have the if save, flash success etc.

提交回复
热议问题