首页 > 解决方案 > 不在显示页面而是在索引页面显示项目列表

问题描述

请你帮帮我吧..

我有三个模型: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

查看 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>

查看 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>

我真正需要什么:我需要通过单击日期按钮在索引页面上显示菜肴列表。(当用户单击工作日按钮时,他需要查看项目菜单列表(在我的实现菜中))

但正如你所见,我在展示页面上制作了展示盘......你能给我一些建议吗?我该如何实现它?

标签: ruby-on-rails

解决方案


您可以尝试使用 AJAX 请求。在这里,我添加了一个带有日期按钮的 AJAX 请求。

# 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>

在这里,我为 JS 请求添加了一个视图文件。

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

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

在这里,我添加_dishes.html.erb部分用于渲染菜肴。

# 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 %>
&lt;/h3>
  </div>
  
<% end %>

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

享受 :-)


推荐阅读