Rails:加载部分数组

时间:2013-04-17 18:02:00

标签: ruby-on-rails arrays renderpartial

在我的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目录并只渲染每个文件。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

定义一个更合适的简单方法(也许是app helper?),如下所示:

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