【问题标题】:NoMethodError when trying to get data from two models on one view尝试从一个视图上的两个模型获取数据时出现 NoMethodError
【发布时间】:2014-01-07 12:25:19
【问题描述】:

好的,我是 Rails 新手,但我正在努力学习,如果这个问题暴露了我缺乏知识,我深表歉意!

我有一个非常简单的应用程序,其中包含 2 个模型(建筑和定制)和 2 个控制器(建筑和定制),每个模型都有一个索引视图。

我的根是建筑物#index

在buildings#index 视图中,我试图从两个模型中访问数据:

    <div class="wrap">
            <header>

                <% @setup.each do |customise| %>

                <h1><%= customise.title %></h1>

                <% end %>

我在建筑物控制器中定义的位置:

    def index

@buildings = Building.all
@unis = Building.where(buildingtype: "uni")

if params[:parentd].present?
@buildings = Building.where("university = ? OR buildingtype = 'directlet'", params[:parentd])

@setup = Customise.all

end

这会产生以下错误:

ActionView::Template::Error (undefined method `each' for nil:NilClass):
4:  
5: <% end %>
6: 
7: <% @unis.each do |uni| %>
8: <option value="<%= uni.name %>"><%= uni.name %></option>
9: <% end %>
app/views/customises/index.html.erb:7:in 
  `_app_views_customises_index_html_erb__589235851577785880_2190604320'

我的阅读表明,在任何视图中访问两个模型的数据都是可能的,这让我相信我的符号有问题。

但是,当我尝试访问相同的模型信息时,以相同的方式但在与 customises 控制器关联的视图中,数据显示没有错误。

任何人都可以提出这背后的原因吗?

【问题讨论】:

  • 我认为在你的控制器中 if 条件没有得到满足所以@setup 是 nil
  • 谢谢。我愚蠢地没有注意到它在 IF 语句中!非常感谢
  • 我可以把它作为答案,这样你就可以接受:)

标签: ruby-on-rails nomethoderror


【解决方案1】:

您的Customise Model 是否包含任何数据?如果是,那么请检查您的情况是

if params[:parentd].present?

你没有得到你的params,即[:parentd]

【讨论】:

    【解决方案2】:

    在你的控制器中,if 条件没有得到满足,所以@setupnil。确保 @setup 被初始化。

    【讨论】:

      【解决方案3】:

      错误undefined method `each' for nil:NilClass表明你试图在nil类的实例上调用方法#each

      在您的情况下,@unisnil(来自您提供的日志)。

      您可以确保 @unit 在控制器中永远不会是 nil。 或者尝试将其放入您视图中的 if..else 块中。

      例如:

      <% if @unit.nil? %>
        <%# Show message regarding nil value of @unit %>
      <% else %>
        <%# Your normal logic of showing @unit %>
      <% end %>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-04-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-20
        相关资源
        最近更新 更多