【问题标题】:Why do I get the error 'undefined method `each' for nil:NilClass' in Ruby on Rails?为什么我在 Ruby on Rails 中收到错误“undefined method `each' for nil:NilClass”?
【发布时间】:2013-07-06 13:34:47
【问题描述】:

我是 RoR 的新手,我非常感谢任何帮助!

我的“索引”文件中有这段代码,但我想将它移动到我的“应用程序”文件中,以便它出现在每个页面的导航中:

<ul class="blogs">
  <% @blogs.each do |blog| %>
    <li>  
      <%= link_to blog.name, blog.url, { :target => 'main-iframe'} %>
      <%= link_to 'Edit', edit_blog_path(blog) %>
    </li>
  <% end %>
</ul>
<%= link_to 'New Blog', new_blog_path %>

这可以正常工作并正确显示。然而,“编辑”和“新博客”链接根本不起作用,它们将我带到下面的错误页面(请注意,当它们在索引页面中时,链接工作正常):

博客中的 NoMethodError#new

nil:NilClass 的未定义方法 `each'

具体问题是这一行:

<% @blogs.each do |blog| %>

该 URL 仍然正确 (/blogs/new),但该行似乎阻止了此页面上的某些内容。

在我的 blogs_controller.rb 页面中,我有(以及其他一些内容):

def index
  @blogs = Blog.all
end
def new
  @blog = Blog.new
end
def edit
end

谁能帮我解决这个问题?

谢谢

【问题讨论】:

  • 你能在new.html.erb上发布代码吗?

标签: ruby-on-rails ruby html


【解决方案1】:

如果您希望它出现在多个页面上,您应该创建一个前置过滤器:

before_filter :load_blogs

def load_blogs
  @blogs = Blog.all
end

def index 
end

一些备注:

  • 考虑缓存数据,而不是每次加载页面时都查询数据库
  • 考虑使用分页,如果博客太多,.all 可能会使您的应用膨胀

【讨论】:

    【解决方案2】:

    因为在新操作中@blogs 为零。你可以试试

    def new
      @blogs = Blog.all
      @blog = Blog.new
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-01-12
      • 2022-11-14
      • 1970-01-01
      • 2013-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多