ruby-on-rails - 不在显示页面而是在索引页面显示项目列表
问题描述
请你帮帮我吧..
我有三个模型: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>
我真正需要什么:我需要通过单击日期按钮在索引页面上显示菜肴列表。(当用户单击工作日按钮时,他需要查看项目菜单列表(在我的实现菜中))
但正如你所见,我在展示页面上制作了展示盘......你能给我一些建议吗?我该如何实现它?
解决方案
您可以尝试使用 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 %>
</h3>
</div>
<% end %>
<script>
$('#closeLink').click(function(e) {
e.preventDefault();
$(this).parent().html("");
});
</script>
享受 :-)
推荐阅读
- javascript - TinyMCE - 未捕获的异常:使用本地 javascript 文件时模块 [5] 返回未定义
- java - 使用模式在 Java 中重复代码重构
- sql - SQL 查询运行缓慢 - 参数嗅探
- graphql - 无法在单个 GraphQL 查询中组合本地和远程数据(Next.js + Apollo)
- arrays - 查找两个数组之间匹配值的字典替代方法
- r - dplyr if else 没有 else
- javascript - 如何遍历 Vue 组件的子组件
- jakarta-ee - 在 Websphere 上实现 Jaeger 开放式跟踪
- java - 要接受 -d @json ,在 rest api 中应该如何写 put 方法
- javascript - parseFloat 将摄氏温度的 NaN 返回到华氏温度