2011-04-10 71 views
3

在我application.html.erb佈局即時渲染部分共享/ _menu.html.erb包含下面的代碼哪裏菜單部分代碼屬於

<nav> 
    <ul> 
    <% Post.all.each do |post| %> 
     <%= link_to post.title, post.permalink %> 
    <% end %> 
    </ul> 
</nav> 

,我做出事實從我的角度來看,模型在尊重MVC的意義上似乎相當麻煩。有沒有人有建議,我應該如何解決這個問題?

+0

的可能重複(HTTP ://stackoverflow.com/questions/4297269/whats-the-rails-way-to-load-other-models-collections-for-new-edit-update-and-cr) – 2011-04-10 11:34:54

回答

4

添加before_filter到您的ApplicationController:

before_filter :define_posts 

def define_posts 
    @posts = Post.all 
end 

那麼你的菜單看起來應該:

<nav> 
    <ul> 
    <% @posts.each do |post| %> 
     <%= link_to post.title, post.permalink %> 
    <% end %> 
    </ul> 
</nav> 

另一種方法是在你的ApplicationController創建的helper方法:

helper_mathod :posts 

def posts 
    @posts ||= Post.all 
end 

所以你可以直接從菜單中調用它:

<nav> 
    <ul> 
    <% posts.each do |post| %> 
     <%= link_to post.title, post.permalink %> 
    <% end %> 
    </ul> 
</nav> 

第二種方法看起來不太清潔。

而且一個時下解決方案是使用Decent Exposure gem:?什麼是軌道的方式來加載新的,編輯更新等車型的集合,並創建行動]

http://railscasts.com/episodes/259-decent-exposure