Reputation: 233
There's 1 comment for Post #2. When I try to create the first comment for Post #1, I get
/posts/1/comments/2
On comment's index page, it lists the same comments for all Posts, regardless of their ID.
comments_controller
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.build(comment_params)
@comment.user = current_user
respond_to do |format|
if @comment.save
format.html { redirect_to [@post, @comment], notice: 'It was successfully created.' }
format.json { render action: 'index', status: :created, location: @comment }
else
format.html { render action: 'new' }
format.json { render json: @comment.errors, status: :unprocessable_entity }
end
end
end
routes
resources :posts do
resources :comments
end
Upvotes: 0
Views: 47
Reputation: 53038
On comment's index page, it lists the same comments for all Posts, regardless of their ID.
You must have defined CommentsController#index
as below:
def index
@comments = Comment.all
end
which is why on comment's index page, you see same comments for all posts.
Assuming that you have nested routes as:
resources :posts do
resources :comments
end
Update CommentsController#index
as below:
def index
@post = Post.find(params[:post_id])
@comments = @post.comments
end
Upvotes: 2
Reputation: 2493
You should drop the database and recreate it again in order to start counting from the beginning.
rake db:drop
rake db:create
It is all about auto increment feature for keys (like :id) in databases.
Upvotes: 0