Home > Blockchain >  Passing correct variable to partial in Rails
Passing correct variable to partial in Rails

Time:10-13

I am trying to show all the companies in a portfolio in Rail 7 and can't figure out the right variable(s) to pass from the Portfolios page to the Companies partial. The companies model has_many: portfolios and Portfolios has_many: companies. Any help would be greatly appreciated.

In Portfolios\index.html.erb, I have tried

<%= render "portfolios/companies", company: portfolio.company_id%> 
<%= render "portfolios/companies", @company %> 
<%= render "portfolios/companies", portfolio: @portfolio %>

In the partial porfolios/_companies.html.erd, I have tried

<%= render portfolio.companies %>
<%= render 'companies/company', @company %>

Each had different errors, such as NilClass and "Undefined local variable or method `company'"

CodePudding user response:

It sounds like you want to display every company for every portfolio on one page... that sounds a little messy but it can be done.

This assumes your index action sets @portfolios. In portfolios\index.html.erb:

<table>
  <thead>
    <td>Portfolio</td>
    <td>Company list</td>
  </thead>
  <tbody>
    <% @portfolios.each do |portfolio| %>
      <tr>
        <td><%= portfolio.name %></td>
        <td>
          <%= render "portfolios/companies", companies: portfolio.companies %>
        </td>
      </tr>
    <% end %>
  </tbody>
</table>

Then in porfolios/_companies.html.erb, the companies variable would contain a collection of companies:

<ul>
  <% companies.each do |company| %>
    <li><%= company.name %></li>
  <% end %>
</ul>

The result should look something like:
enter image description here

  • Related