【问题标题】:Why submitting an invalid post breaks a micropost feed (Railstutorial chapter 11)?为什么提交无效帖子会破坏微博提要(Railstutorial 第 11 章)?
【发布时间】:2015-11-22 05:08:31
【问题描述】:

Hartl's Railstutorial 的第 11 章已经完成了一半,它展示了如何将微博提要添加到主页。它通过代码做到这一点:

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

其中 feed 是方法

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

现在在主页上,假设微博提要是您的部分内容:

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

现在教程在首页提到,如果你提交一个无效的微博,它会崩溃:

“在微博提交失败时,主页需要一个@feed_items 实例变量,因此失败的提交当前会中断。”

我不明白为什么会中断。 @feed_items 不应该包含数据库中所有其他有效的微博吗?所以即使你提交了一个无效的帖子,@feed_items 也会被之前的有效微博填充?我不明白无效的微博如何影响@feed_items,尤其是因为@feed_items 从数据库中提取微博,由于提交的微博上存在验证,因此该数据库仅包含有效的微博。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-4 ruby-on-rails-3.2 railstutorial.org


    【解决方案1】:

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

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

    【讨论】:

    • 我不太确定@feed_items 是如何变为 nil 的,因为它正在从数据库中提取微博,其中包含有效的微博。我在这里遗漏了什么吗?
    • 因为如果微博提交失败,那么您的params 中将没有有效的id,因此您的feed 方法将不起作用,因此您的@feed_items 将不会人口稠密。现在清楚了吗?
    【解决方案2】:

    提交微博时,调用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 实例变量定义为空数组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-07
      • 1970-01-01
      • 2023-01-08
      • 2011-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多