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

时间:2020-05-14 13:07:31

标签: ruby-on-rails ruby ruby-on-rails-5

我在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控制台中查看所有服务。

有人可以帮我吗?

1 个答案:

答案 0 :(得分:3)

您在错误的控制器和操作中设置了变量。

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

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

尝试类似的东西:

class PagesController < ApplicationController
  ...

  def home
    @services = Service.all
  end
end