My topic model is
class Topic < ActiveRecord::Base
has_many :posts
accepts_nested_attributes_for :posts
validates_presence_of :topic
validates :topic, length: { minimum: 3 }
end
My post model is
class Post < ActiveRecord::Base
belongs_to :topic, counter_cache: true
validates_length_of :title ,:minimum => 3
validates_length_of :description,:minimum => 5
end
My Topic controller is
class TopicsController < ApplicationController
before_action :set_topic, only: [:show, :edit, :destroy, :update]
def index
@topics = Topic.all
end
end
My Topic index is
<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>
I want to display the first two posts associated with the topic in the topic's index. I used limit
for that, but can I do this using ruby without passing any query to db?