简体   繁体   中英

Ruby on rails - Showing featured posts?

I am creating a blog application with Ruby on Rails and would like to show 30 'featured' articles on the home page.

I have considered using a boolean attribute 'featured' on the articles table, however I have some issues with this;

  1. If I have 4000 articles, I have to search through all of them just to find the 30 that are featured.
  2. 3970 articles will have an empty column.

I'm wondering if there is a better way - such as creating another DB table that stores just the ID's of the featured articles?

Thanks in advance.

I think in your case the best decision would be to use model scope for featured articles.

class Article < ApplicationRecord
  scope :featured, -> { where(featured: true) }
end

and use this scope from your rails view

<% @articles.featured.each do |article| %>
  <p><%= link_to article.subject, article_path(article) %></p>
<% end>

Link to scopes from Ruby on Rails Guide

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM