任务声音的完整描述:编辑用户显示页面以显示用户的第一个微帖子的内容。(根据文件中的其他内容,运用您的技术技巧(框1.1)猜测语法。)通过访问/users/1确认它工作了。
我的第一个想法是将app/views/users/show.html.erb更新为
<p id="notice"><%= notice %></p>
<p>
<strong>Name:</strong>
<%= @user.name %>
</p>
<p>
<strong>Email:</strong>
<%= @user.email %>
</p>
<p>
<strong>Content:</strong>
<%= @micropost.content %>
</p>
<%= link_to 'Edit', edit_user_path(@user) %> |
<%= link_to 'Back', users_path %>
但似乎我没有得到任务背后的想法?有什么建议我应该从什么开始?非常感谢您的回复)
4条答案
按热度按时间zzoitvuj1#
你应该得到一个
Undefined method 'content' for nil:NilClass
错误。问题是@micropost
没有在控制器方法(action)中定义,nil
也是如此。你不能在
nil
对象上调用content
方法,因为它不响应它。换句话说,在NilClass
上没有定义名为content
的示例方法。要修复此错误,请在
UsersController
的show
操作中定义一个示例变量@micropost
。@user.microposts.first
返回用户的第一篇文章。如果用户没有相关的帖子,
@user.microposts.first
将返回nil
。因此,在视图中显示@micropost
之前,必须检查它是否为nil
。w8biq8rn2#
我想你可以在users/show.html.erb中这样做:
虽然不是很优雅,但它是最简单的,并且满足了练习中“编辑用户显示页面”的要求。
7ivaypg93#
我还添加了@ user.id,因为如果没有它,您就不知道将微帖子添加到哪个用户进行测试。然后,你需要测试,看看是否有一个microposts为了不打破代码试图显示nil。
bwitn5fc4#
我在#def show中将以下内容添加到user_controller.rb中
然后添加到show.html.erb