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?

1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.