[英]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.