Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to render comments controller in Rails on model validations failure?

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
like image 676
ab217 Avatar asked Mar 03 '11 00:03

ab217


1 Answers

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.

like image 105
Pan Thomakos Avatar answered Oct 20 '22 20:10

Pan Thomakos