我在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控制台中查看所有服务。
有人可以帮我吗?
答案 0 :(得分:3)
您在错误的控制器和操作中设置了变量。
如果您希望@services
实例变量在home.html.erb
视图中可用,则需要在PagesController#home
中设置该数据。
如果您以正确的操作设置了变量,然后在home
视图(无论是_show
还是其他视图)中渲染了局部变量,您将可以访问该变量。
尝试类似的东西:
class PagesController < ApplicationController
...
def home
@services = Service.all
end
end