TL;DR How can I achieve this behavior? Is it there any other method I could particularly use?
I have a Rails application that has blog functionality. I am trying to display all recent posts in descending order but with no luck. Here are my sources:
app/controllers/blog_controller.rb
class BlogController < ApplicationController before_filter :authenticate_user!, except: [:index, :show] before_filter :set_blog, only: [:show, :edit, :update, :destroy]def index @blog = Blog.allenddef new @blog = Blog.newenddef create @blog = Blog.new(blog_params) redirect_to_blog_on(@blog.save, :error_template => :new, :notice => 'Post successfully posted.') enddef update redirect_to_blog_on(@blog.update(blog_params), :error_template => :edit, :notice => 'Post updated successfully.')enddef destroy @blog.destroy respond_to do |format| format.html { redirect_to blog_index_url, :notice => 'Post deleted successfully.' } endendprivatedef set_blog @blog = Blog.find(params[:id])enddef blog_params params.require(:blog).permit(:title, :content)enddef redirect_to_blog_on(condition, error_template: nil, notice: '') respond_to do |format| if condition format.html { redirect_to @blog, notice: notice } format.json { render :show, status: :created, location: @blog } else format.html { render error_template } format.json { render json: @blog.errors, status: :unprocessable_entity } end end end end
Upon show.html.erb, I have a title and body content to begin with and I thought I could do some Latest Posts
code but it failed me miserably.
app/views/blog/show.html.erb
<div class="container"><h1><%= @blog.title %><hr></h1><div class="row"><div class='col-md-4'><p><i class="glyphicon glyphicon-time"></i> Date Posted: <%= @blog.created_at.to_s(:long) %></p></div><div class="col-md-offset-0"><p><% if @blog.created_at != @blog.updated_at %><i class="glyphicon glyphicon-ok"></i> Updated at: <%= @blog.updated_at.to_s(:long) %><% end %></p></div></div><br><div class="row"><div class="col-lg-7"><p><%= markdown @blog.content %></p><div class="col-md-3"><% if user_signed_in? %><%= link_to edit_blog_path(@blog) do %><i class="glyphicon glyphicon-edit"></i> Edit<% end %><% end %></div><div class="col-md-3"><% if user_signed_in? %><%= link_to blog_path(@blog), method: :delete, data: { confirm: 'Are you sure?' } do %><i class="glyphicon glyphicon-trash"></i> Delete Post<% end %><% end %></div></div><div class="col-md-offset-8"><h4>Latest Posts</h4><% if @blog.present? %><% @blogs.each do |blog| %><%= link_to blog_path(blog) do %><%= blog.title %><% end %><% end %><% else %><h3>Check back later!</h3><% end %></div></div></div>