2013-04-17 75 views
0

在我Rails應用程序的陣列我已經有下面的代碼:Rails的:加載中諧音

<% %w(number_of_students edit_class_name tech_help).each do |modal| %> 
    <%= render "common/modals/#{modal}" %> 
<% end %> 

會有一些更多的模態加入app/views/common/modals,而是明確地列舉出來的%w()我想循環訪問common/modals目錄並只渲染每個文件。

回答

1

這裏是我想出了:

def render_modals 
    files = Dir.glob("#{Rails.root}/app/views/common/modals/*").collect { |file| File.basename(file, ".html.erb").sub("_", "") }.flatten 

    files.collect do |modal| 
     render partial: "common/modals/#{modal}" 
    end.join.html_safe 
    end 
0

定義在哪裏比較合適(也許應用助手?)這樣一個簡單的方法:如果你需要這些模態在

def modals 
    %w(number_of_students edit_class_name tech_help) 
end 

一個控制器/模型,也許你應該在適當的類中定義這個方法?例如

class Modal 
    def self.types 
    %w(number_of_students edit_class_name tech_help) 
    end 
end 

另外,如果您經常渲染模板,然後還定義

def render_modals 
    modals.map do |modal| # Modals here should be the method that you just defined, example, Modal.types 
    render partial: "common/modals/#{modal}" 
    end.join 
end