PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, May 18, 2022

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

 May 18, 2022     partial, ruby-on-rails     No comments   

Issue

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.



Answered By - Tinus Wagner
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing