Rails - 在保留表单数据的同时,如何在注释错误后重定向回发布?

时间:2014-02-19 15:22:27

标签: ruby-on-rails ruby ruby-on-rails-4

我有一个基本的帖子/评论设置。在这里,我将它们称为引脚和回复,但分别适用相同的格式。

我的回复(评论)嵌套在别针(帖子)下。当我提交带有错误的回复时,我会重定向回到引脚,但表单上输入的任何数据都将丢失。我想保留这个。

replies_controller.rb

def create

    @pin = Pin.find(params[:pin_id])

    @reply = @pin.replies.build(params[:reply].permit(:reply))
    @reply.user_id = current_user.id
    @reply.save

    if @reply.save
        flash[:success] = "Reply successfully created"
        redirect_to pin_path(@pin)
    else

        if @reply.errors.any?
            flash[:warning] = "#{@reply.errors.count} Problems found: #{@reply.errors.full_messages.to_sentence}"
        end

        redirect_to pin_path(@pin)

    end

end

因为它进行了重定向,我认为这就是擦除表单的原因。我如何处理错误,以便呈现我刚刚来自的引脚(post)的视图,而不是重定向?

感谢一堆! 迈克尔。

2 个答案:

答案 0 :(得分:2)

请勿重定向:

render 'pins/new'

答案 1 :(得分:0)

使用render代替redirect

def create
  @pin = Pin.find(params[:pin_id])

  @reply = @pin.replies.build(params[:reply].permit(:reply))
  @reply.user_id = current_user.id
  @reply.save

  if @reply.save
    flash[:success] = "Reply successfully created"
    redirect_to pin_path(@pin)
  else
    if @reply.errors.any?
      flash[:warning] = "#{@reply.errors.count} Problems found: #{@reply.errors.full_messages.to_sentence}"
    end
    render :template => "pins/show"
  end
end