繁体   English   中英

Ruby on Rails 教程 (Michael Hartl) 第 2 章练习 2.3.3.1 “编辑用户显示页面以显示用户第一个微博的内容。”

[英]Ruby on Rails Tutorial (Michael Hartl) Chapter 2 Exercise 2.3.3.1 “Edit the user show page to display the content of the user’s first micropost.”

任务声音的完整描述:编辑用户展示页面以显示用户第一条微博的内容。 (使用您的技术熟练程度(框 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 %>

但似乎我对任务没有想法? 我应该从什么开始的任何建议? 非常感谢您的回复)

Undefined method 'content' for nil:NilClass错误,您应该得到一个Undefined method 'content' for nil:NilClass 问题是@micropost没有在控制器方法(动作)中定义,所以是nil

并且您不能在nil对象上调用content方法,因为它不响应它。 换句话说,在NilClass上没有定义名为content实例方法。

要修复错误, @micropostUsersControllershow操作中定义一个实例变量@micropost

# users_controller.rb

def show
  @user = User.find(params[:id])
  @micropost = @user.microposts.first
end

@user.microposts.first返回用户的第一篇文章。

如果用户没有与之关联的帖子, @user.microposts.first将返回nil 因此,您必须先检查@micropost是否为nil然后才能在视图中显示它。

# users/show.html.erb

<% if @micropost %> 
  <p>
    <strong>Content:</strong>
    <%= @micropost.content %>
  </p>
<% end %>

我认为您可以在 users/show.html.erb 中执行此操作:

@user.microposts.first.content

虽然不优雅,但它是最简单的,满足练习的“编辑用户显示页面”的要求。

我还添加了@user.id 因为没有它你不知道将微博添加到哪个用户进行测试。 然后您需要测试以查看是否有微博,以免破坏试图显示 nil 的代码。

<p>
  <strong>ID:</strong>
  <%= @user.id %>
</p>


<% if @user.microposts.first %>
<p>
  <strong>First Post:</strong>
  <%= @user.microposts.first.content %>
</p>
<% end %>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM