rails视图文件中的高效编码

时间:2013-02-10 01:50:20

标签: ruby-on-rails views

这些是我的控制器,视图和部分文件。 我的问题是部分文件中的第二行。我想在这里写DRAFTS当项目等于@drafts并且当项目等于@completed时我​​想写完全。我可以修复它吗?

controller.rb

def projects
    @projects = @user.projects
    @drafts = @user.projects.draft
    @currents = @user.projects.current
    @completed = @user.projects.ended
    @user.projects.completed.each do |c|
      @completed << c
    end
    @all_projects = [@drafts,@currents,@completed]
  end

查看文件

<% for projects in @all_projects %>
  <%= render :partial => 'user_projects', :locals => {:projects => projects} %>
<% end %>

部分档案

<div class="panel">
        <h3>PROJECTS GENERAL NAME</h3>
        <div class="panel_contents">
          <% if projects.length == 0 %>
            <h2>There is no project.</h2>
          <% else %>
              <div class="attributes_table">
                <table cellspacing="0",cellpadding="0",border="0">
                  <thead>
                    <tr>
                      <th>Project Name</th>
                      <th>Created</th>
                      <th>Ended</th>
                      <th>Duration</th>
                      <th>Condition</th>
                      <th>Prize</th>
                    </tr>
                  </thead>
                  <tbody>
                     <% projects.each do |project| %>
                      <tr>
                        <td><%= link_to project.title, admin_projects_path('search[id_equals]' => project.id) %></td>
                        <td><%= l project.created_at, :format => :default  if project.created_at %></td>
                        <td><%= l project.end, :format => :default  if project.end %></td>
                        <td><%= Brief.find_by_project_id(project.id).duration  %></td>
                        <td><%= project.stage %></td>
                        <td><%= number_to_currency project.prize %></td>
                      </tr>
                    <% end %>
                  </tbody>
                </table>
              </div>
          <% end %>  
        </div>
      </div>

1 个答案:

答案 0 :(得分:0)

最简单的方法是在partial中使用'projects.first'。假设该字符串位于名为status

的属性下
<h3><%= projects.first.status %></h3>

下面更复杂的解决方案

<% [[@drafts, 'Drafts'], [@completed, 'Completed']].each do |projects, title| %>
  <%= render 'user_projects', :projects => projects, :title => title %>
<% end %>

 # partial
<h3><%= title %></h3>