簡體   English   中英

Ruby on Rails檢測到用戶,但仍返回不存在的錯誤

[英]Ruby on Rails detecting a user, but still returning an error that it doesn't exist

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的create動作。 現在,當我嘗試訪問發布路徑時,出現以下錯誤: <%= 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本身。所以我更改了帖子模板,以打印出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我收到一條錯誤消息,說Thought甚至沒有用戶,但是當我檢查它們時,我發現該想法有一個用戶,而該用戶有一個用戶名。 我想念什么嗎? 是什么原因造成的? 我應該去哪里看? 如果需要,我可以提供更多信息。

提前致謝!

編輯:這是服務器輸出:

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

我認為,您可以通過以下方式為表單建立思想

@new_thought = @post.thoughts.build

之后,@ post.thoughts也包括@new_thought。 @ new_thought.user為零。 這就是為什么您會得到500錯誤的原因。 您可以修改視圖:

<%- if thought.persisted? ->
 -- your code
<%- end -%

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM