在Hartl的“铁路报”第11章中,我已经读了一半,它展示了如何在主页中添加微帖子提要。它通过代码执行此操作:
@feed_items = current_user.feed.paginate(page: params[:page])在哪里进给是方法
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从数据库中提取微博,数据库中只包含有效的微博,因为在提交的微博上存在验证。
发布于 2015-11-22 05:14:06
因为这样,@feed_items将是nil,当您在视图中调用:@feed_items.any?时,这将是nil.any?,该错误消息将失败:
NoMethodError: undefined method `any?' for nil:NilClass发布于 2016-04-25 14:33:20
当您提交微信时,您将调用MicropostsController的MicropostsController操作
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如果micropost成功保存,您将被重定向。调用home的StaticPagesController动作。那时,@micropost和@feed_items都是创建的。一切都很好。
如果micropost不成功地保存不保存,那么您将停留在StaticPagesController中,并尝试呈现static_pages/home模板。为此,您需要@micropost和@feed_items实例变量,但此时您只定义了@micropost。
这就是为什么建议的解决方法是在尝试呈现模板之前将@feed_items实例变量定义为空数组。
https://stackoverflow.com/questions/33851818
复制相似问题