Rails 4 - 选择性地显示部分表格字段

时间:2016-04-02 02:48:08

标签: ruby-on-rails ruby-on-rails-4

我正在尝试显示我的Job模型的两个不同的表格表示,每个表格中显示不同的字段:

dashboard.html.erb

...
<table class="table table-bordered table-hover table-striped">
  <thead>
    <tr>
      <th>Job #</th>
      <th>Job Name</th>
      <th>Due Date</th>
      <th>Progress</th>
    </tr>
  </thead>
  <tbody>
    <%= render @jobs_due_soon %> <!-- version 1 -->
  </tbody>
</table>

...

<table class="table table-bordered table-hover table-striped">
  <thead>
    <tr>
      <th>Job #</th>
      <th>Job Name</th>
      <th>Cut At</th>
    </tr>
  </thead>
  <tbody>
    <%= render @jobs_completed %> <!-- version 2 -->
  </tbody>
</table>
...

_job.html.erb 版本1

<tr>
  <td><%= job.number %></td>
  <td><%= job.name %></td>
  <td><%= job.due_date %></td>
  <td><%= job.progress %></td>
</tr>

_job.html.erb 第2版

<tr>
  <td><%= job.number %></td>
  <td><%= job.name %></td>
  <td><%= job.cut_at %></td>
</tr>

实现这一目标的最佳方法是什么?我可以有两个不同的部分,并根据我正在显示的表调用每个部分。我也可以传入一个指定版本1或2的局部变量。但是,这些选项都不是解决问题的正确方法。

1 个答案:

答案 0 :(得分:0)

有两种方法可以做到这一点,具体取决于您希望如何分离责任。我不熟悉你的代码库,所以类和变量名只是为了获得一般的想法。

将报告逻辑放入作业模型:

# job.rb
# ------

  def Job.jobs_due_soon
    # logic for generating the data needed for your jobs due soon table
  end

  def Job.jobs_completed
    # logic for generating the data needed for your jobs completed table
  end


# jobs_controller.rb
# ------------------

  def dashboard
    @jobs_due_soon = Job.jobs_due_soon
    @jobs_completed = Job.jobs_completed
    render :dashboard
  end


# dashboard.html.erb
# ------------------

  <%= render 'table', data: @jobs_due_soon %>
  <%= render 'table', data: @jobs_completed %>


# _table.html.erb
# ---------------

  # format according to the how you set up the output of Job::jobs_due_soon 
  # and Job::jobs_completed.
  #
  # see second example for suggestions on how to iterate over data of
  # dynamic length in the table.

将数据逻辑放入控制器:

# jobs_controller.rb
# -------------

  def dashboard
    @table_one_data = [job.name, job.number, job.due_date, job.progress]
    @table_one_body = jobs_due_soon
    @table_two_data = [job.number, job.name, job.cut_at]
    @table_two_body = jobs_completed
    render :dashboard
  end

# dashboard.html.erb
# ------------------

  <%= render 'table', row_data: @table_one_data, table_body: @table_one_body %>
  <%= render 'table', row_data: @table_two_data, table_body: @table_two_body %>


# _table.html.erb
# ------------------

  # format according to how you set up the output of Job::jobs_due_soon and 
  # Job::jobs_completed