RoR はかなり新しいですが、単純なアプリを構築するために使用していて、問題が発生しています。
基本的に、私のアプリは User、Post、Thought の 3 つのモデルを使用します。ユーザーがユーザーである場合、投稿はユーザーが作成できる投稿であり、思考は投稿に対するコメントのようなものです。
投稿の考えを投稿の下に表示しようとしています。投稿のページには、各思考のテンプレートを作成する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 自体に接続していない。だから私は投稿テンプレートを 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'
ここに私の考え.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