Search code examples
ruby-on-railspartial

How to render slightly difference partial in "index" page and "show" page


There is a model Company that has many DailyDatum.

I want to show the daily data in companies/:id/daily_data and daily_data/index. But in the company's page I don't want to show company.name column.

views/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>

views/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>

views/companies/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>

How should I handle situation like this? Does I need to create another partial HTML?


Solution

  • This might be overkill since you're only trying to conditionally render one single field, but the "right" approach would be to create a helper.

    I'd recommend creating a helper to conditionally render one of two partials for @daily_data depending on the 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
    

    Then in your views you can simply call:

    <% render_appropriate_partial %>
    

    And it will render the appropriate partial based on which route/url your on.