在Rails中显示嵌套资源的错误消息
我正在创建我的第一个应用程序,简单的博客,我不知道如何显示未通过validation的嵌套资源(注释)的错误消息。
这是为评论创建动作:
def create @post = Post.find(params[:post_id]) @comment = @post.comments.create(comment_params) redirect_to post_path(@post) end
这是评论表:
我尝试过:
def create @post = Post.find(params[:post_id]) @comment = @post.comments.build(comment_params) if @comment.save redirect_to post_path(@post) else render '/comments/_form' end end
和:
prohibited this comment from being saved:
但我不知道什么是错的。
您无法从控制器渲染部分。 更好的选择就是创建一个new
视图。
class CommentsController def create if @comment.save redirect_to post_path(@post), success: 'comment created' else render :new end end end
应用程序/视图/评论/ new.html.erb:
<% if @comment.errors.any? %> <%= pluralize(@comment.errors.count, "error") %> prohibited this comment from being saved:
<% @comment.errors.full_messages.each do |msg| %> - <%= msg %>
<% end %>
<% end %> <%= render partial: 'form', comment: @comment %>
应用程序/视图/评论/ _form.html.erb:
<%= form_for([@post, local_assigns[:comment] || @post.comments.build]) do |f| %> <%= f.label :commenter %>
<%= f.text_field :commenter %>
<%= f.label :text %>
<%= f.text_area :text %>
<%= f.submit %>
<% end %>
- 使用词典重构Ruby on Rails i18n YAML文件
- Rails 3.1一个表单上的多个对象
- Rails – 每个子域单独的数据库
- 测试rake任务中定义的方法
- 如何正确配置rails test以在浏览器中运行它? (site_prism,黄瓜,水豚,seleniumwebdriver)
- RESTful设计,如何命名CRUD等人的页面?
- sass-rails资产管道:错误地生成图像路径; `url(/images/blah.png)`而不是`url(/assets/blah.png)`
- Rails中的HTML标题属性仅显示第一个单词
- 如何从rails应用程序上的ruby获取mongodb数据库和集合列表的列表