Rails初学者 - 时间与nil的比较失败

时间:2014-06-20 15:29:54

标签: ruby-on-rails

我正在浏览此Blogger教程http://tutorials.jumpstartlab.com/projects/blogger.html#i3:-tagging

并且我继续进行"时间与零的比较失败"添加

时出错
<p>Posted <%=distance_of_time_in_words(comment.article.created_at, comment.created_at) %> later<p>

至我的评论部分(_comments.html.erb)

这是我的架构

ActiveRecord::Schema.define(version: 20140618233420) do

  create_table "articles", force: true do |t|
    t.string   "title"
    t.string   "body"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "comments", force: true do |t|
    t.string   "author_name"
    t.text     "body"
    t.integer  "article_id"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  add_index "comments", ["article_id"], name: "index_comments_on_article_id"

 end

有人可以解释一下吗?我的rails服务器指示注释和文章都有时间戳,所以它们如何显示为nil?

以下是我的_comment.html.erb文件中的完整代码

<div>
    <h4>Comment by <%= comment.author_name %></h4>
    <p class="comment"><%= comment.body %></p>
    <p>Posted <%=distance_of_time_in_words(comment.article.created_at, comment.created_at) %> later<p>

</div>

这是我的控制器代码:

class CommentsController < ApplicationController

    def create
        @comment = Comment.new(comment_params)
        @comment.article_id = params[:article_id]

        @comment.save

        redirect_to article_path(@comment.article)
    end

    def comment_params
        params.require(:comment).permit(:author_name, :body)
    end
end

1 个答案:

答案 0 :(得分:0)

确保代码中包含此内容:

<%= render partial: 'articles/comment', collection: @article.comments %>

<强> /models/comment.rb

class Comment < ActiveRecord::Base
  belongs_to :article
end