显示两个模型的静态页面上的重复



我正在尝试创建一个静态页面杂志显示两种不同的模型体验的文章按日期排序

然而,我遇到了一个奇怪的问题,体验模型在杂志页面上复制。

页面控制器:

class PagesController < ApplicationController
include Pagy::Frontend
def home
@experiences = Experience.order('date DESC').limit(1)
@articles = Article.order('date DESC').limit(1)
end
def magazine
@experiences = Experience.order('date DESC')
@articles = Article.order('date DESC')
@feed = (@experiences.to_a + @articles.to_a).sort_by(&:date)
end
end

静态杂志视图页面:

<% if @feed.any? %>
<% @feed.each do |feed| %>
<% if feed.is_a? Experience %>
<div id="articles" align="center">
<% @experiences.each do |experience| %>
<div class="article-widget">
<%= link_to experience do %>
<%= image_tag experience.picture_url, :class=> "img-rounded", width: '80%' if experience.picture.present? %>
<% end %>
<div class="article-top-left"><h3><%= experience.category %></h3></div>
<div class="article-bottom-left"><h4><%= experience.title %><br /> <%= experience.location %></h4></div>
</div>
<% end %>
</div>
<% else %>
<% if feed.is_a? Article %>
<div id="articles" align="center">
<% @articles.each do |article| %>
<div class="article-widget">
<%= link_to article do %>
<%= image_tag article.picture, :class=> "img-rounded", width: '80%' if article.picture.present? %>
<% end %>
<div class="article-top-left"><h3><%= article.category %></h3></div>
<div class="article-bottom-left"><h4>Around London with <%= article.title %><br /></h4></div>
</div>
<% end %>
</div>
<% end %>
<% end %>
<% end %>
<% end %>

我不能发现任何明显的控制器或视图页面,将使经验模型复制,但我真的是新的编码,所以如果有人可以帮助,将是非常感激!非常感谢

问题是您正在循环组合feed,然后为每个feed项目循环@experiences@articles

<% if @feed.any? %> # you don't need if since the loop will run 0 times if there are no records 
<% @feed.each do |feed| %>
<% if feed.is_a? Experience %>
<div id="articles" align="center">
<% @experiences.each do |experience| %> # <-- this is where it goes wrong

如果两个代码分支之间只有一个很小的区别,您可以极大地简化这段代码:

<% @feed.each do |feed_item| %>
<div id="articles" align="center">
<div class="article-widget">
<%= link_to feed_item do %>
<%  if feed_item.picture %>
<!-- You should really consider the accessibility impacts of this. -->
<!-- see https://www.w3.org/WAI/tutorials/images/functional/ -->
<%= image_tag feed_item.picture, 
class: "img-rounded", 
width: "80%",
alt: "A text which describes the link"
%>
<% else %>
<!-- You should provide fallback content if there is no image! -->
<% end %>
<% end %>
<div class="article-top-left">
<h3><%= feed_item.category %></h3>
</div>
<div class="article-bottom-left">
<!-- This could be refactored into a helper method --> 
<% if feed_item.is_a? Article %>
<h4>Around London with <%= feed_item.title %></h4>
<% else %>
<h4><%= feed_item.title %></h4>
<% end %>
</div>
</div>
</div>
<% end %>

最新更新