如何在"索引"页面和"显示"页面中呈现略有差异的部分

iro*_*and 1 ruby-on-rails partial

有一个模型Company有很多DailyDatum.

我想在companies/:id/daily_data和中显示每日数据daily_data/index.但在公司的页面中我不想显示company.name专栏.

视图/ daily_data/_daily_datum.html.erb

<tr>
  <td><%= daily_datum.company.name %></td>
  # This company.name needs to be shown when the partial is called from daily data index.
  <td><%= daily_datum.column1 %></td>
  <td><%= daily_datum.column2 %></td>
</tr>
Run Code Online (Sandbox Code Playgroud)

视图/ daily_data/index.html.erb

<table>
  <thead>
  <tr>
    <th>Company Name</th>
    <th>Daily Datum1</th>
    <th>Daily Datum2</th>
  </tr>
  </thead>
  <%= render @daily_data %>
</table>
Run Code Online (Sandbox Code Playgroud)

意见/公司/ daily_data.html.erb

<table>
  <thead>
  <tr>
    <!--<th>Company Name</th>-->
    <th>Daily Datum1</th>
    <th>Daily Datum2</th>
  </tr>
  </thead>
  <%= render @daily_data %>
</table>
Run Code Online (Sandbox Code Playgroud)

我应该怎样处理这样的情况?我是否需要创建另一个部分HTML?

Tin*_*ner 5

这可能是过度的,因为你只是试图有条件地渲染一个单独的字段,但" 正确 "的方法是创建一个帮助器.

我建议创建一个帮助器来有条件地渲染两个部分之一,以@daily_data取决于path.

companies_helper.rb

def is_companies_index_path?
  current_page?(companies_index_url)
end

def is_companies_show_path?
  current_page?(companies_show_url)
end

def render_appropriate_partial
  render 'daily_data_a' if is_companies_index_path?
  render 'daily_data_b' if is_companies_show_path?
end
Run Code Online (Sandbox Code Playgroud)

然后在您的视图中,您可以简单地致电:

<% render_appropriate_partial %>
Run Code Online (Sandbox Code Playgroud)

它将根据您的路线/网址呈现适当的部分.