如何遍历已推广Post?模型方法调用及视图实现咨询
如何在视图中调用Post模型的推广方法遍历已推广帖子
首先,你的Post模型已经定义了两个关键方法来处理推广帖子:
- 实例方法
promoted?:判断单个帖子是否属于推广状态 - 类方法
promoted_posts:直接从数据库查询所有活跃订阅的推广帖子(效率更高,因为是数据库层面的筛选)
下面给你两种实现方式,优先推荐第一种:
方案1:在控制器中准备数据(推荐遵循MVC原则)
视图的核心职责是展示数据,最好不要在视图里做数据筛选逻辑。你可以在对应的控制器动作中,直接获取已推广的帖子集合:
# 比如在你的PostsController的index方法里 def index # 获取前6个已推广的帖子(直接在数据库层面完成筛选和数量限制) @promoted_posts = Post.promoted_posts.take(6) end
然后修改视图代码,遍历@promoted_posts即可:
<% @promoted_posts.each do |post| %> <div class="col-xs-6 col-sm-6 col-md-6 col-lg-4"> <div class="featured-box"> <figure> <%= link_to image_tag(post.images.first, class: 'img-fluid'), post %> </figure> <div class="feature-content"> <div class="product"> <p><%= post.category.name %> / <%= post.subcategory.name %></p> </div> <h4><%= link_to post.title, post %></h4> <ul class="address"> <li> Ad#: <%= post.ad_number %> </li> <li> posted <%= time_ago_in_words(post.created_at) %> ago </li> <li> <%= post.state%> , <%= post.city.downcase %> </li> </ul> <div class="listing-bottom"> <h3 class="price float-left">$<%= post.price%></h3> <%= link_to 'Feature Ad', post, class: 'btn-verified float-right', style: 'color: red;' %> </div> </div> </div> </div> <% end %>
方案2:在视图中直接过滤(不推荐,仅作参考)
如果你临时需要在视图里筛选,也可以使用promoted?实例方法过滤现有@posts集合,但这种方式会先加载所有@posts到内存再筛选,数据量大时效率较低:
<% @posts.select(&:promoted?).take(6).each do |post| %> <!-- 这里保留你原来的视图内容即可 --> <% end %>
额外说明
你的模型里的promoted_posts方法已经通过joins和where筛选了活跃订阅的帖子,比在内存中用promoted?筛选更高效,所以优先用类方法获取数据。
内容的提问来源于stack exchange,提问作者Andy Walker
相关产品推荐
相关产品推荐

