2012-08-01 19 views
2

有什麼辦法可以在一個索引頁面列出多個模型?多個模型在一個索引頁面

就像我有4個模型:用戶,機構,授權人員和導師,我想列在一個索引頁面中。

是否有我可以遵循的特定過程?

回答

0

您可以直接查詢所有這些在控制器的index動作:

class MyController < ApplicationController 
    def index 
    @users = User.all 
    @agencies = Agency.all 
    @authorized_people = AuthorizedPerson.all 
    @mentors = Mentor.all 

    respond_to do |format| 
     format.html 
    end 
    end 

    # ... 
end 

而在你的意見中引用它們正常:

<% @agencies.each do |agency| %> 
    <!-- do stuff --> 
<% end %> 

<% @users.each do |user| %> 
    <!-- do more stuff --> 
<% end %> 

<!-- etc. --> 
+0

我試過你的步驟,但它給了我一個錯誤,我看不到運行應用程序時的字段。我做了一個腳手架來創建模型/視圖/控制器文件。現在,如果我想在一個視圖中使用多個模型,是否是一種好的方法?我是否必須向模型文件和數據庫遷移文件添加一些內容?在這方面指導我。 – Rubyuser 2012-08-02 18:16:04

0

Rubyuser,

是,這是完全正常的行爲。在您的控制器中,無論何時使用@myvariable指定變量,它都是控制器和視圖範圍內的實例變量。沒有@的變量是僅在該方法中可用的局部變量。

所以在您的控制器,當你做:

class Foos < ApplicationController 
    def index 
     @foos = Foo.all 
     @bars = Bar.all 
    end 
end 

之後就可以引用@foos和@bars從您的視圖中。

<h1>My foos and bars</h1> 
<table> 
<thead> 
    <th>foo</th> 
</thead> 
<tbody> 
    <% @foos.each do |f| %> 
    <tr> 
    <td>f.name</td> 
    </tr> 
    <% end %> 
</tbody> 
</table> 

<table> 
<thead> 
    <th>bar</th> 
</thead> 
<tbody> 
    <% @bars.each do |b| %> 
    <tr> 
    <td>b.name</td> 
    </tr> 
    <% end %> 
</tbody> 
</table> 

現在,爲了讓事情更乾淨,您可能需要考慮使用部分。創建一個名爲_bars_index.html.erb的文件,並將其中的條形碼複製到表格中。

<%= render "bars_index" %> 

,現在你的代碼是好的,整潔,易於遵循更換。

相關問題