I have a simple Video model in my rails app that has_many
comments. I am displaying these comments on the video's show page. When I submit the form everything works fine; however, if there are validation errors on the Comment model, then my system blows up. If there are validation errors on the Comment model, I would simply like to render the video's show page again, with the validation error styling showing. How do I do this inside of my create action? Thanks a lot!
class CommentsController < ApplicationController
def create
@video = Video.find(params[:video_id])
@comment = @video.comments.build(params[:comment])
if @comment.save
redirect_to @video, :notice => 'Thanks for posting your comments.'
else
render # what? What do I render in order to show the video page's show action with the validation error styling showing? Please help!
end
end
end
To do this you'll have to render a template:
class CommentsController < ApplicationController
def create
@video = Video.find(params[:video_id])
@comment = @video.comments.build(params[:comment])
if @comment.save
redirect_to @video, :notice => 'Thanks for posting your comments.'
else
render :template => 'videos/show'
end
end
end
Keep in mind that you'll have to declare any instance variables (like @video) inside of the CommentsController#create action as well though, because the VideosController#show action will not be run, the template will simply be rendered. For instance, if you have an @video_name variable in your VideosController#show action, you'll have to add the same @video_name instance variable to the CommentsController#create action.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With