如何按类型和最近日期调用实例 rails

How to call instances by type and most recent date rails

我有一个博客 post,我想将其放在 2 个不同的显示视图中。我希望显示最近的 4 个 post,但我所有的 post 都是 2 个不同 :post_types(经理或用户)中的 1 个。所以我想要 1 个视图显示 4 个最近的经理 post,另一个视图显示 4 个最近的用户 post。我应该把这个逻辑、控制器或模型中的某个地方放在哪里,我如何制作一个方法来获取每种类型的 4 个最近的 post?

目前我在控制器中有这个

def index

  @blog1 = Post.order(:date => :desc).first 
  @blog2 = Post.order(:date => :desc).offset(1).first
  @blog3 = Post.order(:date => :desc).offset(2).first
  @blog4 = Post.order(:date => :desc).offset(3).first

end

但它不会按类型

分隔post

这将完成工作:

def index
  @manager_posts = Post.where(post_type: 'Manager').order('date DESC').limit(4)

  @user_posts    = Post.where(post_type: 'User').order('date DESC').limit(4)
end

那么在你看来

<% @manager_posts.each do |manager_post| %>
  <%= manager_post.content %>
<% end %>

<% @user_posts.each do |user_post| %>
  <%= user_post.content %>
<% end %>

这个好像懂了

@blog1 = Post.where(:post_type == 'Manager' ).order(:date => :desc).first