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

前端 未结 2 1531
长情又很酷
长情又很酷 2020-12-05 20:47

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

2条回答
  •  孤街浪徒
    2020-12-05 21:28

    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.

提交回复
热议问题