【发布时间】:2020-05-14 13:07:31
【问题描述】:
我的 ruby on rails 项目中有一个服务模型,但我无法在我的项目的 pages#home 视图中呈现它我得到了这个 undefined method `each' for nil:NilClass 虽然我已经在我的 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 控制台中的所有服务。
有人可以帮帮我吗?
【问题讨论】:
-
如果你想在
PagesController#home处理请求时设置实例变量@services = Service.all,你需要在that方法中实际设置实例变量。在另一个控制器中设置实例变量绝对没有任何作用。 Rails 中的show显示一条记录。index对应记录的集合。 -
谢谢它成功了,我在我的 pagesconroller 中移动了 @services=Service.all 并且它成功了。谢谢
标签: ruby-on-rails ruby ruby-on-rails-5