0

RoR 很新,但我用它来构建一个简单的应用程序,我遇到了一个问题。

基本上我的应用程序使用三个模型:用户、帖子和思想。在用户是用户的情况下,帖子是用户可能发布的帖子,而想法就像对帖子的评论。

我试图让帖子的想法显示在帖子下方。在帖子的show.html.erb页面上,我调用了<%= render @thoughts %>,它会_thought.html.erb为每个想法生成模板。模板如下所示:

<div>
    <li>
        <%= link_to thought.user.username, thought.user %>
        <span class="content"><%= thought.content %></span>
        <span class="timestamp"> Posted <%= time_ago_in_words(thought.created_at) %> ago.       </span>
    </li>
</div>

这以前可行,但现在我在底部添加了一个表单并稍微更改了 ThoughtsController 的创建操作。现在,当我尝试访问帖子路径时,我收到此错误:<%= link_to thought.user.username, thought.user %> - undefined method 'username' for nil:NilClass. 即使我将视图更改为仅显示用户名,我也会收到此错误,如下所示:<%= thought.user.username %>

我想,很公平,有些地方出了问题,这些想法可能不再与用户联系起来。当我试图测试它时,发生了一些奇怪的事情。我将思想视图更改为仅显示“ thought.inspect()”。然后页面加载正常,第一个想法显示如下:

<Thought id: 55, content: "Tenetur ut et sit nulla nesciunt modi eos.",
post_id: 295, user_id: 40, penny: false, created_at: "2013-08-26 21:37:55",
updated_at: "2013-08-26 21:37:55">

我想,“嗯,这很奇怪。它似乎有一个 user_id。可能它没有连接到 User 本身。所以我将帖子模板更改为 print out thought.user.inspect()。现在第一个想法返回:

#<User id: 40, username: "example_user39", created_at: "2013-08-26 21:37:41",
updated_at: "2013-08-26 21:37:41", password_digest:
"$2a$10$7urQB56QdkdXdNedsMe/KuENUTsQ.nk9FjKgLcE98sW6...",
remember_token: "336856d5e046b96983848f39d9e450aaa496252d", admin: false>

所以我很困惑。当我尝试打印时,thought.user.username我收到一个错误,说思想甚至没有用户,但是当我检查它们时,我发现思想有一个用户并且用户有一个用户名。我错过了什么吗?这可能是什么原因造成的?我应该去哪里看?如有必要,我可以提供更多信息。

提前致谢!

编辑:这是服务器输出:

Completed 500 Internal Server Error in 21ms
ActionView::Template::Error (undefined method 'username' for nil:NilClass):
    1: <div>
    2:  <li>
    3:          <%= link_to thought.user.username, thought.user %>
    4:          <span class="content"><%= thought.content %></span>
    5:          <span class="timestamp"> Posted <%= time_ago_in_words(thought.created_at) %> ago. </span>
    6:  </li>
  app/views/thoughts/_thought.html.erb:3:in '_app_views_thoughts__thought_html_erb___991787178796439758_70190024095460'
  app/views/posts/show.html.erb:10:in '_app_views_posts_show_html_erb__1664758191839643789_70190022800060'

这是我的 Thought.rb:

class Thought < ActiveRecord::Base
  belongs_to :post
  belongs_to :user
  validates :user_id, presence: true
  validates :post_id, presence: true
  validates :content, presence: true
  default_scope -> { order('created_at DESC') }
end
4

1 回答 1

0

I think, you build your thought for form in way like this:

@new_thought = @post.thoughts.build

After that, @post.thoughts includes @new_thought, too. And @new_thought.user is nil. That's why you get 500 error. You can modify your view:

<%- if thought.persisted? ->
 -- your code
<%- end -%
于 2013-08-28T06:39:54.267 回答