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

前端 未结 3 811
小鲜肉
小鲜肉 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:25

    Something like this should do what you want:

    flash[:notice] = "Post can not be saved, please enter information."
    render :new
    

    UPDATE: You updated your question so I have to update my answer. Render is the right way to do this. However, it looks like you load some categories and some other collection of stuff in your new method. Those same instance variables should be available to your create method. The cleanest way to do this is put them into another method and have that method used as a before_filter applied to both create and new. Something like this:

    before_filter :load_stuff, :only => [:create, :new]
    
    def load_stuff
      @arr_select = { 1=>"One",2=>"Two" ,3=>"Three" }
      @categories_select = Category.all.collect {|c| [ c.category_name, c.id ] }
    end
    

    Then your new method is pretty much blank and calling render :new in your create method should work.

提交回复
热议问题