Jonathan
Jonathan

Reputation: 683

Get Most Recent Post

Currently I'm trying to get only the most recent post in my index view that is marked as 'featured'.

In my controller I have

@featured = Post.featured

In my 'Post' Model I have

scope :featured, -> { where(:featured => true) }

And in my view I have

  <% @featured.each do |post| %>
   <%= post.title %>
  <% end %>

What I'm trying to do is literally just get the first post that is marked as featured.

Any help is greatly appreciated, thanks in advance!

Upvotes: 1

Views: 68

Answers (1)

Andrew Hendrie
Andrew Hendrie

Reputation: 6415

Try this in your controller:

@featured = Post.featured.order("created_at").last

Note: if you're only storing one featured post in the @featured instance variable then you can change your view code to this:

<%= @featured.title %>

It isn't necessary to loop over one item with the each method.

Upvotes: 2

Related Questions