2011-01-07 42 views
0

我試圖顯示此發現的輸出 -軌 - 顯示嵌套發現哈希

@test = User.joins(:plans => [:categories => [:project => :presentations]]).where(current_user.id) 

這裏是我的輸出循環

<% @test.each do |p| %> 
    <%= p.plans %> 
    <% p.plans.each do |d| %> 
    <%= debug(d) %> 
    <% d.categories.each do |e| %> 
     <% e.project.each do |r| %> 
     <%= debug(r) %> 
     <% end %> 
<% end %> 
    <% end %> 
<% end %> 

循環工作,直到它到達時,它拋出項目這個錯誤

undefined method `each' for "#<Project:0x000001033d91c8>":Project 

如果我在循環將其更改爲項目它給這個錯誤

undefined method `projects' for #<Plan:0x000001033da320> 

在類別級別調試顯示了這個

--- !ruby/object:Category 
attributes: 
id: 2 
name: test 
short_name: tst 
created_at: 
updated_at: 
category_id: 2 
plan_id: 5 

我的關係是這樣的

用戶 的has_many:user_plans 計劃 的has_many:user_plans has_and_belongs_to_many:類 類別 HAS_ONE:項目 has_and_belongs_to_many:計劃 項目 的has_many:演示:依賴=>:DELETE_ALL 介紹 belongs_to的:項目

我需要改變我的發現?

謝謝,亞歷克斯

回答

1

類別HAS_ONE:項目

所以它是單一的對象不是集合因此沒有each方法。

+0

謝謝,應該是has_many – Alex 2011-01-07 15:48:21

1

根據你的關係定義,Category只有has_one項目,那麼你爲什麼要迭代e.project?如果你只是想顯示調試輸出,更換

<% e.project.each do |r| %> 
    <%= debug(r) %> 
<% end %> 

<%= debug(e.project) %> 

但是,如果你想更深入,進入演示,這樣做:

<%= debug(e.project) %> 
<% e.project.presentations.each do |presentation| %> 
    <%= debug(presentation) %> 
<% end %> 
1

你的問題是你在單個對象上調用數組方法。

category.project會給你一個單一的項目對象嗎?這不是一個數組,所以你不能調用它。

替換此:

<% e.project.each do |r| %> 
<%= debug(r) %> 
<% end %> 

debug(e.project) 

當你在這,這裏的一些其他方面的建議:使用描述性的變量名。爲什麼'p'表示測試,'d'表示計劃,'e'表示類別等?變量名稱應該告訴你對象是什麼。同樣,我期望變量@test來保存一個Test對象。在你的代碼中,它似乎是一個數組。對於包含該類型對象集合的變量,使用複數變量名 - 例如@plans將是一個Plan對象數組。

<% @tests.each do |test| %> 
    <% test.plans.each do |plan| %> 
    <%= debug(plan) %> 
    <% plan.categories.each do |category| %> 
    <%= debug(category.project) %> 
    <% end %> 
    <% end %> 
<% end %> 

是不是更具有可讀性?

+0

這就是我的黑客和有點懶惰的完成版本看起來像你:) – Alex 2011-01-07 16:28:08