Adam Lazarus
Adam Lazarus

Reputation: 134

rails - NoMethodError in PostsController#create undefined method `post_url'

I'm writing a simple website in which users (authenticated with Devise) can create posts. Upon creating a new post, I'm running into this error in which it won't redirect to the post. Here's my Posts controller:

class PostsController < ApplicationController
  before_filter :authenticate_user!

  def new
    @post = current_user.posts.new
  end

  def create
    @post = current_user.posts.new(post_params)
    if @post.save
      redirect_to @post
    end
  end

  def show
    @post = Post.find_by_id(params[:id])
  end

  private
    def post_params
      params.require(:post).permit(:title, :content)
    end
end

Here's my routes.rb:

Rails.application.routes.draw do
  devise_for :users
  resources :users do
    resources :posts 
  end
  root 'posts#new'
end

Since the posts resource is nested within users I thought perhaps I should have this in my controller:

if @post.save
      redirect_to current_user.@post
    end

But that produces a SyntaxError in PostsController#create error.

Can anyone see the problem that's preventing the controller from redirecting to the post after it's created? Any help would be much appreciated.

Upvotes: 0

Views: 1040

Answers (2)

dp7
dp7

Reputation: 6749

Try this -

redirect_to [current_user,@post]

OR,

redirect_to user_post_path(current_user, @post)

hope it helps!

Upvotes: 3

margo
margo

Reputation: 2927

In your model, have you allowed for nested attributes? In the controller you want to use build instead of new.

Upvotes: 0

Related Questions