我在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控制台中使用所有服务。有人可以帮我吗?
如果要在@services
视图中使用home.html.erb
实例变量,则需要在PagesController#home
中设置该数据。
如果您以正确的操作设置了变量,然后在home
视图中渲染了局部视图,无论是_show
还是其他视图,您都可以访问该变量。
尝试类似的东西:
class PagesController < ApplicationController
...
def home
@services = Service.all
end
end
@services
可能为零,请检查@services的绑定,然后查看@service的实际值。