【发布时间】:2019-01-20 22:55:12
【问题描述】:
我的主题模型是
class Topic < ActiveRecord::Base
has_many :posts
accepts_nested_attributes_for :posts
validates_presence_of :topic
validates :topic, length: { minimum: 3 }
end
我的帖子模型是
class Post < ActiveRecord::Base
belongs_to :topic, counter_cache: true
validates_length_of :title ,:minimum => 3
validates_length_of :description,:minimum => 5
end
我的主题控制器是
class TopicsController < ApplicationController
before_action :set_topic, only: [:show, :edit, :destroy, :update]
def index
@topics = Topic.all
end
end
我的主题索引是
<h1>Topics</h1>
<table class="table">
<% @topics.each do |t| %>
<%= link_to t.topic,topic_posts_path(topic_id: t.id) %><%= "(# .
t.posts_count})" %><br>
<% @post= t.posts.limit(2) %>
<% @post.each do |p| %>
<li>
<%=link_to p.title,topic_post_path(topic_id: p.topic_id,id: p.id) %><br>
</li>
<% end %>
<%= link_to "more..", topic_posts_path(t.id)%><br>
<% end %><br>
<%= link_to "Add Topic",new_topic_path %>
</table>
我想在主题索引中显示与该主题相关的前两个帖子。我为此使用了limit,但是我可以使用 ruby 来执行此操作而不向 db 传递任何查询吗?
【问题讨论】:
-
group_by在您的问题中的作用是什么? -
@JagdeepSingh 我不想将查询传递给 db 。我想使用 ruby 命令来获取前两条记录。那么我可以使用 group_by 吗?
-
要显示零帖子的主题吗?
-
@JagdeepSingh 不,我想显示与每个主题相关的前两个帖子。但不使用任何查询,如 limit,last
-
我知道您希望显示每个主题的前两个帖子。但是帖子为零的主题呢?应该显示它们吗?
标签: ruby-on-rails ruby