为什么提交无效的 post 会破坏 micropost 提要(Railstutorial 第 11 章)?

Why submitting an invalid post breaks a micropost feed (Railstutorial chapter 11)?

我已经读完 Hartl 的 Railstutorial 第 11 章的一半了,该章介绍了如何向主页添加微型 post 提要。它通过代码做到这一点:

@feed_items = current_user.feed.paginate(page: params[:page])

其中 feed 是方法

  def feed
    Micropost.where("user_id = ?", id)
  end

现在在主页中,微post 提要应该是您有一个部分包含:

<% if @feed_items.any? %>
  <ol class="microposts">
    <%= render @feed_items %>
  </ol>
  <%= will_paginate @feed_items %>
<% end %>

现在教程提到在主页上,如果您提交无效的微post,它会崩溃:

"on failed micropost submission, the Home page expects an @feed_items instance variable, so failed submissions currently break."

我不明白为什么会中断的解释。 @feed_items 不应该由数据库中所有其他有效的 micropost 组成吗?这样一来,即使您提交了无效的 post,@feed_items 也会填充先前有效的 micropost?我不明白无效的 micropost 是如何影响 @feed_items,特别是因为 @feed_items 从数据库中提取 microposts,它只包含有效的 micro posts 因为提交的 microposts 上存在验证。

因为那时 @feed_items 将是 nil 并且当您调用: @feed_items.any? 在您看来,那将是 nil.any? 并且将失败并显示以下错误消息:

NoMethodError: undefined method `any?' for nil:NilClass

提交微博时,调用了MicropostsControllercreate动作:

def create
@micropost = current_user.microposts.build(micropost_params)
if @micropost.save
  flash[:success] = "Micropst created"
  redirect_to root_url
  else
    render 'static_pages/home'
end
end

如果微博保存成功,您将被重定向。 StaticPagesControllerhome 动作被调用。 @micropost@feed_items 都被创建了。一切正常。

如果微博没有保存成功,那么你就停留在StaticPagesController,尝试渲染static_pages/home模板。为此,您需要 @micropost@feed_items 实例变量,但此时您只定义了 @micropost

这就是为什么建议的解决方法是在尝试呈现模板之前将 @feed_items 实例变量定义为空数组。