2016-02-27 22 views
-1

我在我的Rails應用程序頁腳顯示了兩個實例變量在welcome_controller.rb生產的所有最近的職位和類別如何避免同樣的實例變量,頁腳

不過,如果我去有另一節一個不同的控制器負責我得到一個錯誤,因爲@posts和@categories實例變量沒有循環並列出最新的帖子和類別。

welcome_controller.rb(代碼片段)

@categories = Category.all 
@posts = Post.order("created_at DESC") 

_footer.html

<div class="row footer-black"> 
    <div class="large-3 columns text-left"> 
     <h4>Categories</h4> 
     <ul> 
     <% @categories.each do |c| %> 
      <% unless c.header? %> 
      <% if c.restriction %> 
       <% if check_for_free_questions_in_restricted_category(c) %> 
       <li> <%= link_to c.title, category_random_free_question_path(c),'data-no-turbolink' => true %> </li> 
       <% else %> 
       <li> <%= link_to c.title, new_subscription_path,'data-no-turbolink' => true %> </li> 
       <% end %> 
      <% else %> 
       <li> <%= link_to c.title, category_random_question_path(c),'data-no-turbolink' => true %> </li> 
      <% end %> 
      <% end %> 
     <% end %> 
     </ul> 
    </div> 
    <div class="large-5 columns text-left"> 
     <h4>Latest Posts</h4> 
     <ul> 
     <% @posts.each do |p| %> 
      <li> <%= link_to truncate(p.title, length:70), blog_post_path(p) %> </li> 
     <% end %> 
     </ul> 
    </div> 
    <div class="large-4 columns text-left social-links"> 
     <h4>Social</h4> 
     <a href="#"> 
     <i class="fa fa-facebook-square fa-2x"></i> 
     </a> 
     <a href="#"> 
     <i class="fa fa-twitter-square fa-2x"></i> 
     </a> 
     <a href="#"> 
     <i class="fa fa-google-plus-square fa-2x"></i> 
     </a> 
    </div> 
    </div> 

有沒有辦法來顯示頁腳類別和職位沒有了一遍又一遍相同的實例變量?

回答

1

簡短的回答是'不'。每個變量必須實例化(初始化)纔可以使用(在這種情況下,在您的看法)。

現在,有實例化這些變量不是寫作的一些更有效的方法:

@categories = Category.all 
@posts = Post.order("created_at DESC") 
在多個控制器

。但是,這是一個不同的問題。如果你對此感興趣,那麼可以提出一個新問題或者改進這個問題。