ActionView :: Template :: Error(nil:NilClass的未定义方法'each'):?

问题描述 投票:0回答:2

我在ruby on rails项目中有一个服务模型,但是无法在我项目的pages#home视图中呈现它。我得到了这个[[nil:NilClass的未定义方法'each'在我的Servicecontroller中定义了变量-

我的ServicesController文件-

class ServicesController < ApplicationController def show @services = Service.all end end

我的节目文件-

<div class="container"> <h3>Services we offer-</h3> <% @services.each do |service| %> <h5><%= service.name %></h5> <p><%= service.description %></p> <% end %> </div>

并且我的服务视图显示文件的路径是此app\views\services\_show.html.erb,并且在页面视图app\views\pages\home.html.erb中将其呈现为<%= render 'services/show' %>,尽管我仍然可以看到,但仍然出现错误使用@ services = Service.all命令在Rails控制台中使用所有服务。 

有人可以帮我吗?

ruby-on-rails ruby ruby-on-rails-5
2个回答
3
投票
您在错误的控制器和操作中设置了变量。

如果要在@services视图中使用home.html.erb实例变量,则需要在PagesController#home中设置该数据。

如果您以正确的操作设置了变量,然后在home视图中渲染了局部视图,无论是_show还是其他视图,您都可以访问该变量。

尝试类似的东西:

class PagesController < ApplicationController ... def home @services = Service.all end end


0
投票
我认为@services可能为零,请检查@services的绑定,然后查看@service的实际值。
© www.soinside.com 2019 - 2024. All rights reserved.