Michael Hartl教程第11章未定义的方法

时间:2015-03-04 00:46:51

标签: ruby-on-rails

我正在阅读Hartls教程,但稍作修改。我坚持用作者连接微博。

我有以下错误:

 undefined method `content' for #<Post:0x4cea7b8>
Extracted source (around line #4):

<li id="post-<%= post.id %>">
<%= link_to gravatar_for(post.user, size: 50), post.user %>
<span class="user"><%= link_to post.user.name, post.user %></span>
<span class="content"><%= post.content %></span>
<span class="timestamp">
Posted <%= time_ago_in_words(post.created_at) %> ago.
</span> 

我的_post.html.erb

<li id="post-<%= post.id %>">
  <%= link_to gravatar_for(post.user, size: 50), post.user %>
  <span class="user"><%= link_to post.user.name, post.user %></span>
  <span class="content"><%= post.content %></span>
  <span class="timestamp">
    Posted <%= time_ago_in_words(post.created_at) %> ago.
  </span>
</li>

我的用户/ show.html.erb

<% provide(:title, @user.name) %>
<h1>
  <%= gravatar_for @user %>
  <%= @user.name %>
</h1>
<div class="col-md-8">
  <% if @user.posts.any? %>
      <h3>Microposts (<%= @user.posts.count %>)</h3>
      <ol class="posts">
        <%= render @posts %>
      </ol>
      <%= will_paginate @posts %>
  <% end %>
</div>

我的schema.rb文件

  create_table "comments", force: true do |t|
    t.text      "body"
    t.integer   "user_id"
    t.integer   "post_id"
    t.timestamp "created_at"
  end

  create_table "posts", force: true do |t|
    t.text     "message"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "user_id"
  end

  add_index "posts", ["user_id", "created_at"], name: "index_posts_on_user_id_and_created_at"
  add_index "posts", ["user_id"], name: "index_posts_on_user_id"

schema.rb其余的

create_table "users", force: true do |t|
    t.string   "name"
    t.string   "email"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "password_digest"
    t.string   "remember_digest"
    t.boolean  "admin"
    t.string   "activation_digest"
    t.boolean  "activated",         default: false
    t.datetime "activated_at"
  end

  add_index "users", ["email"], name: "index_users_on_email", unique: true
  add_index "users", ["name"], name: "index_users_on_name", unique: true

end

1 个答案:

答案 0 :(得分:0)

在您的_post.html.erb文件中,将<span class="content"><%= post.content %></span>更改为<span class="content"><%= post.message %></span>,它应该有效。

您收到“未定义方法”错误的原因是,当您创建Post模型时,您使用“message”作为属性名称,但在_post.html.erb文件中,您尝试访问不存在的“内容”属性。