Rails 文章评论不满足格式要求,显示错误问题

runup · 2013年09月10日 · 最后由 shawnyu 回复于 2013年09月10日 · 2099 次阅读

源码:https://github.com/runup520/blog_three 环境:ubuntu13.04 ruby1.9.3 rails3.2.13 sqlite3 使用了 sunspot 全文检索,所以可能要用到语句:rake sunspot:solr:start

写了一个博客项目,想在文章评论不满足要求的情况下,,返回该页面,并且显示哪些错误。

报错原因:undefined method `errors' for nil:NilClass 就是说可能这个@comment没有传入进来。我在 articles_controller.rb 中添加了@comment的变量,

@article = Article.find(params[:id])
@comment = @article.comments.find_by_id(params[:id])

这两句代码是否有错呢? 前台显示用了 partial, 代码如下所示:

<section>

  <%=@comment%>

<% if @comment.errors.any? %>
  <div id="error_explanation">
    <div class="alert alert-error">
      The form contains <%= pluralize(@comment.errors.count, "error") %>.
    </div>
    <ul>
    <% @comment.errors.full_messages.each do |msg| %>
      <li># <%= msg %></li>
      <li># <%[email protected] %></li>
    <% end %>
    </ul>
  </div> 
<% end %>



</section>

请教原因。 我把这些代码去掉之后重新调教可以运行的项目如下 :https://github.com/runup520/blog_fourth

还有我对

@article = Article.find(params[:id])
@comment = @article.comments.find_by_id(params[:id])

params 里面的东西为什么这么些,理解的不是很透彻,求一些材料指点,除了官方网站提供的。

params 里面是每次 http 请求的参数。你可以在 rails server 的 log 中看到他们。

上例你请求的是 /articles/1 这样的路径 Rails 在处理这个的时候把 1 作为 http 参数中的 id , 这个你可以在文档的路由哪里找到, 所以 params 里面就有一个键'id' 这个作为当前请求的 aritlce 的 id

@comment = @article.comments.find_by_id(params[:id])

这个就没道理了@article.comments 这个找到的是当前文章下的评论。后面的 id 是文章的 id 不是 comment 的 id! 而且这个返回的是一个 Relation 对象 类似一个数组。

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