简体   繁体   中英

Showing latest blog posts in Rails

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.all
end

def new
  @blog = Blog.new
end

def create
  @blog = Blog.new(blog_params)

 redirect_to_blog_on(@blog.save, :error_template => :new, :notice => 'Post successfully posted.')   
end

def update

  redirect_to_blog_on(@blog.update(blog_params), :error_template => :edit, :notice => 'Post updated successfully.')
end

def destroy
  @blog.destroy

  respond_to do |format|
   format.html { redirect_to blog_index_url, :notice => 'Post deleted successfully.' }
 end
end

private

def set_blog
  @blog = Blog.find(params[:id])
end

def blog_params
  params.require(:blog).permit(:title, :content)
end

def 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>

Order your blog posts by date created when retrieving them from the database. Here's how your index action would look:

def index
  @blog = Blog.order("created_at DESC")
end

This retrieves all blog posts from your database by their creation date in descending order. The most recent post will be at the beginning of the array ( @blog[0] ), while the oldest post will be at the very end of the array.

I would recommend you pluralize the instance variable name so you know that it is an array:

def index
  @blogs = Blog.order("created_at DESC")
end

Check out this link for more details on ordering using Active Record.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM