Cdok Cdok - 6 months ago 6x
Ruby Question

Access first X elements in a Class (Ruby / Rails)

I've tested a couple of methods for printing the first 3 instances of my class for a Ruby on Rails application. I've already got the following working :

<%@posts.each do |post| %>
<div class ="post content" >
<h2 class="title"><%=post.title%></h2>
<p class="date"><%= post.created_at.strftime("%B, %d, %Y")%></p>
<p class="body"><%=post.body%></p>
<% end %>

But I'm trying to do the same thing but only printing the first 3 elements of the @posts variable.

.first(3) and .find(:id) haven't worked and I'm at a loss on how to iterate through the class variables.



You want to use take.

<% @posts.take(3).each do |post| %>

You should consider moving this logic in the controller.

first works in a similar manner (but it orders by id), and should get the job done as well.