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

1hdlvixo  于 2023-06-22  发布在  Ruby
关注(0)|答案(4)|浏览(84)

任务声音的完整描述:编辑用户显示页面以显示用户的第一个微帖子的内容。(根据文件中的其他内容,运用您的技术技巧(框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 %>

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

zzoitvuj

zzoitvuj1#

你应该得到一个Undefined method 'content' for nil:NilClass错误。问题是@micropost没有在控制器方法(action)中定义,nil也是如此。
你不能在nil对象上调用content方法,因为它不响应它。换句话说,在NilClass上没有定义名为content的示例方法。
要修复此错误,请在UsersControllershow操作中定义一个示例变量@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 %>
w8biq8rn

w8biq8rn2#

我想你可以在users/show.html.erb中这样做:

@user.microposts.first.content

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

7ivaypg9

7ivaypg93#

我还添加了@ user.id,因为如果没有它,您就不知道将微帖子添加到哪个用户进行测试。然后,你需要测试,看看是否有一个microposts为了不打破代码试图显示nil。

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

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

bwitn5fc4#

我在#def show中将以下内容添加到user_controller.rb中

@user = User.find(params[:id])
@micropost_first = @user.microposts.first.content

然后添加到show.html.erb

<%= @micropost_first %>

相关问题