2

I dont understand how to insert code into my welcome/index.html.erb file. Here is my code:

Welcomes_controller.rb

def index
  @welcomes = Welcome.all
end

Schedules_controller.rb

def index
  @schedules = Schedule.all
end

schedules/index.html.erb

          <table class="table table-hover">
            <thead>
              <tr>
                <th>Время<br>отправления</th>
                <th>Город</th>
                <th>Место<br> отправления</th>
                <th>Время <br>прибытия</th>
              </tr>
            </thead>
            <tbody>
            <% @schedules.each do |s| %>
              <tr>
                <td><%= s.deptime %></td>
                <td><%= s.city %></td>
                <td><%= s.street %></td>
                <td><%= s.aparttime %></td>
              </tr> 
            <% end %>             
            </tbody>
          </table>

How do I insert that code into welcome/index.html.erb?

jacefarm
  • 6,747
  • 6
  • 36
  • 46
i pass
  • 23
  • 3
  • Possible duplicate of [One controller rendering using another controller's views](http://stackoverflow.com/questions/1013152/one-controller-rendering-using-another-controllers-views) – Sahil Nov 16 '16 at 17:23

2 Answers2

1

To render the schedules index template from the welcomes_controller.rb

def index
  @welcomes = Welcome.all
  render "/schedules/index"
end

However, this will present a problem because the table in the view depends on an @schedules instance variable to be set and it will return nil because it is not assigned a value in the controller.

you might want to do this:

def index
  @schedules = Welcome.all
  render "/schedules/index"
end

Which does not really make sense to me from a semantic point of view. You might want to rename the instance variable to something more model agnostic.

In the other answer it was suggested to use a partial. That could actually be a better solution depending on the use case.

veldtmana
  • 176
  • 6
0

create a partial app/views/shared/_index_table.html.erb with the content

<table class="table table-hover">
  <thead>
    <tr>
      <th>Время<br>отправления</th>
      <th>Город</th>
      <th>Место<br> отправления</th>
      <th>Время <br>прибытия</th>
    </tr>
  </thead>
  <tbody>
  <% schedules.each do |s| %>
    <tr>
      <td><%= s.deptime %></td>
      <td><%= s.city %></td>
      <td><%= s.street %></td>
      <td><%= s.aparttime %></td>
    </tr> 
  <% end %>             
  </tbody>
</table>

Then, app/views/schedules/index.html.erb

<h1>Schedules</h1>
<%= render partial: "shared/index_table", :locals => { schedules: @welcomes } %>

and app/views/welcomes/index.html.erb

<h1>Welcome</h1>
<%= render partial: "shared/index_table", :locals => { schedules: @schedules } %>

This works only if you have the same set of attributes (deptime, city, street, aparttime) on both Welcome and Schedule models

sa77
  • 3,563
  • 3
  • 24
  • 37