Search code examples
ruby-on-railsrubyruby-on-rails-3ruby-on-rails-3.1

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


def create
    @addpost = Post.new params[:data]
    if @addpost.save
        flash[:notice] = "Post has been saved successfully."
        redirect_to posts_path
    else
        flash[:notice] = "Post can not be saved, please enter information."
    end
end

If the post is not saved then it redirects to http://0.0.0.0:3000/posts , but i need to stay on the page, with text input fields so that user can input data.

post model

class Post < ActiveRecord::Base

    has_many :comments
    validates :title, :presence => true
    validates :content, :presence => true
    validates :category_id, :presence => true
    validates :tags, :presence => true
end

new method

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

new.html.erb

<h3>Add post</h3>

<%= form_tag :controller=>'posts', :action=>'create' do %>
    <%= label :q, :Title %>
    <%= text_field :data, :title, :class => :addtextsize %><br/>
    <%= label :q, :Content %>
    <%= text_area  :data, :content, :rows=>10 , :class => :addtextarea %><br/>
    <%= label :q, :Category %>
    <%= select :data, :category_id, @categories_select %><br/>
    <%= label :q, :Tags %>
    <%= text_field :data, :tags, :class => :addtextsize %><br/>
    <%= label :q, :Submit %>
    <%= submit_tag "Add Post" %>
<% end %>

What should i do ?


Solution

  • flash.now with render is what you're looking for.

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

    Also instead of

    flash[:notice] = "Post has been saved successfully."
    redirect_to posts_path
    

    you can just write

    redirect_to posts_path, :notice => "Post has been saved successfully."
    

    and it will do the same thing. It works only with redirect_to though, not with render!