Rails 有嵌套路由的情况下,出错时,在 create Action 中如何修改 render new Action 才能将错误带到表单页面?

diguage · 2014年01月13日 · 最后由 Yujing_Z 回复于 2014年01月14日 · 2351 次阅读

最近,遇到一个问题,各种 Google、百度没有找到解决方案。发出来,希望遇到过类似问题的朋友能出手相助。

问题描述

现在有嵌套路由,如下:/users/:user_id/comments/new

如果在CommentsControllercreate Action 中出错的话,该如何修改render action: :new,来把错误带到创建表单页面?

如果没有嵌套路由的情况下,应该是如下:

# POST /comments
# POST /comments.json
def create
  @comment = Comment.build_from(params[:comment])
  respond_to do |format|
    if @comment.save
      format.html { redirect_to @comments, notice: '成功' }
    else
      format.html { render action: "new" }
    end
  end
end

问题:在有嵌套路由的情况下,下面这段代码该如何修改?

format.html { render action: "new" }

@diguage 嵌套和不嵌套没有区别。要怎么修改跟你 View 里面怎么来显示错误有关。

@diguage 加個 notice: '哎呀,出錯啦'

嵌套路由的话楼主的代码确实会出错吧? 在 create 方法第一句加上 @user = User.find params[user_id] 应该就可以了

#3 楼 @blueplanet 如果前台写法标准,这代码就就不会出错

#4 楼 @Yujing_Z 可能我理解的有点问题。 这里不需要获取上一级的 user 的 id? 你的意思是说前台在 comment 的 form 里面写上 user_id?

#1 楼 @yedingding 他说的是对的,当你用 model 的 validation callback 的时候,一旦出错,会把 errors 保存到实例对象里面的。你只是需要想好怎么展示错误而已。比如你的@comment保存出错,错误信息就会保存在@comment.errors里面。

#5 楼 @blueplanet 恩这时候 form 应该是类似user.comments.build

需要 登录 后方可回复, 如果你还没有账号请 注册新账号