jimps jimps - 2 months ago 13
Ruby Question

Rails redirect to the post after a comment is made

I have a comment form on my tickets show page. I can fill it out, but when submitting the comment, it goes to the comments show page. I need this to just go back to the ticket it was showing.

I have this code at the moment:

comment_controller.rb

def create
@comment = Comment.new(comment_params)

respond_to do |format|
if @comment.save
format.html { redirect_to @comment, notice: 'Comment was successfully created.' }
format.json { render :show, status: :created, location: @comment }
else
format.html { render :new }
format.json { render json: @comment.errors, status: :unprocessable_entity }
end
end
end


and a similar thing with the destroy method

def destroy
@comment.destroy
respond_to do |format|
format.html { redirect_to comments_path, notice: 'Comment was successfully destroyed.' }
format.json { head :no_content }
end
end


I'm not sure how to get it to remember which ticket it was on, for it to redirect to.

I have entered the associations with the models with ticket.rb and comments.rb

Answer

You can just replace the

redirect_to comments_path

with

redirect_to :back
# or 
redirect_to(:back)

which after the comment is made, it returns to the previous page

If you're using rails 5, use

redirect_back(fallback_location: root_path)

instead