开发者

Rails views: missing template after render called following failed validation with nested resources

I'm trying to work with failed validations in Rails 3.

I have a chap开发者_高级运维ters resource, with nested comments. There is only one view in total; the show view from the chapters_controller, which contains a form to post a new comment and points to the comments_controller create action as follows (controller code is included):

http://pastie.org/1338126

when it fails validation, it incorrectly routes to: '/chapters/1/comments' and displays the following on the page:

Template is missing

Missing template http://localhost:3000/chapters/1 with {:locale=>[:en, :en], :formats=>[:html], :handlers=>[:rhtml, :rxml, :builder, :erb, :rjs]} in view paths "/app/views", "", "/"

cheers

Paul


For those in the future, I just had a similar problem.

I was trying to render when validation failed for the address create action:

render new_user_address_path(@user)
#Normally this should work with a redirect_to or a link_to but render doesn't work this way

instead you should:

render 'new'

As @ideaasylum mentioned, You can't render a "named helper" but you can render an action. To me, it seems like an idiosyncrasy with rails. Technically a named path and the action should go to the same place.


I think the problem is with the render call:

if @comment.save
  redirect_to chapter_url(params[:chapter_id])
else
  render chapter_url(params[:chapter_id])
end

I don't think it's correct to pass a URL to render (see the api here: http://apidock.com/rails/ActionController/Base/render). Typically you call

render :action => new

which will render the new view of the current controller. Since you want to render the chapter 'show' view (i.e., a different controller's view), I think the call should be more like:

render :template => 'chapters/show'

My Rails knowledge is getting a bit rusty and things could have changed with Rails 3. Hope that helps anyway...


After you redirect, you must return immediately since redirect_to does not return.

 if @comment.save
      redirect_to chapter_url(params[:chapter_id]) and return
    else
      render chapter_url(params[:chapter_id]) and return
    end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜