Why does rails redirect to the show action after creating?

user3277633 picture user3277633 · Mar 11, 2015 · Viewed 10.5k times · Source

New web developer here, and I think I may be missing some very fundamental knowledge. Given the code

def create
        @post = Post.new(post_params)
        if @post.save
            redirect_to @post
        else
            render "new"
        end
end

why does the view templates redirect to the def show action? If I do not define a def show and its corresponding views, rails will throw me an error.

I am just not understanding why even though the code is redirect_to @post after I save a post, it appears to be redirecting to the show page after creating a post. Is this just one of those rails thing that I should just take it as it is or am I missing some fundamental HTML protocol knowledge (which I honestly don't know a lot about)?

Edit: To further clarify my question, I see that @post is already defined in the create method and is defined as Post.new(post_params). when I redirect_to @post, wouldn't it simply call that line again?

Answer

Rajdeep Singh picture Rajdeep Singh · Mar 11, 2015

Lets take a look at your code

def create
  @post = Post.new(post_params)
  if @post.save
    redirect_to @post
  else
    render "new"
  end
end

why does the view templates redirect to the def show action? If I do not define a def show and its corresponding views, rails will throw me an error.

In create action you are creating a new record, so if you look at this part of the code

if @post.save
  redirect_to @post

When @post is successfully saved, we are redirecting it to show action by writing redirect_to @post, the actual route for show action would be post_path(@post) so you can also write redirect_to post_path(@post) but even if you simply pass object with redirect_to rails will redirect it to the show action. Now going to the else part

else
  render "new"

If the @post object is not saved in the database(due to validation), we want to reload the form, so in the above code render is just rendering the view of new action and not calling the new action, only the view is rendered because new.html.erb contains the form.

Hope this helped!