Show list of items not at the show page but at the index page

Viewed 86

May you help me please..

I have three models: Day, Course, Dish

class Day < ApplicationRecord

  has_many :courses

  has_many :dishes, through: :courses

end

class Course < ApplicationRecord

  belongs_to :day

  belongs_to :dish

end
class Dish < ApplicationRecord

  has_many :courses

  has_many :days, through: :courses

end

class DaysController < ApplicationController


  before_action :require_user



  def index

    @days = Day.all

  end


  
  def show

    @day = Day.find(params[:id])

    @dishes = @day.dishes

  end



end

View index.html.erb:

<div class="days">

  <div class="container">

    <% @days.each do |day| %>

      <button>

        <%=day.weekday %>

        <%= link_to "Show menu", day_path(day) %>

      </button>

      <% end %>

    <%= link_to "Back to Profile", profile_dir_path(@user), method: "get" %>

  </div>

</div>

View show.html.erb:

<h2>Menu</h2>

    <% @dishes.each do |dish| %>
 
     <div class="dish">
 
       <h3 class="dish-name"><%= dish.name%></h3>

       <h3 class="dish-description"><%= dish.description%>

          </h3>

    <% end %>

    </div>

  </div>

</div>

What do I really need: I need to display a list of dishes on the index page by clicking on the day button. (When user click on the weekday button he need to see menu list of items (in my implementation dishes))

But as you see I made display dishes on the show page.... May you give a couple of advise how can i realize it?

1 Answers

You can try with AJAX request. Here I have added one AJAX request with day button.

# app/views/days/index.html.erb

<div class="days">

  <div class="container">

    <% @days.each do |day| %>

      <%= button_to day.weekday, day_path(day), data: { remote: true } %>

    <% end %>

    
    <div id="menuList"></div>
    <%= link_to "Back to Profile", profile_dir_path(@user), method: "get" %>

  </div>

</div>

Here I am adding one view file for JS request.

# app/views/days/show.js.erb

$('.days').find('#menuList').html('<%= j (render "dishes", dishes: @dishes) %>');

Here I am adding _dishes.html.erb partial for rendering dishes.

# app/views/days/_dishes.html.erb

<h2>Menu</h2>

<%= link_to "Close", "#", id: "closeLink" %>

<% dishes.each do |dish| %>
 
  <div class="dish">
 
    <h3 class="dish-name"><%= dish.name %></h3>

    <h3 class="dish-description"><%= dish.description %>
</h3>
  </div>
  
<% end %>

<script>
  $('#closeLink').click(function(e) {
    e.preventDefault();
    $(this).parent().html("");
  });
</script>

Enjoy :-)

Related