我如何按日期排序?

时间:2014-03-23 01:05:39

标签: ruby-on-rails

我是rails的新手,我有一个rails应用程序允许我通过提供标题,日期和描述来创建截止日期并创建倒计时,问题是我想按输入的日期排序所有截止日期,如何我在索引方法中做到了吗?

  class DeadlinesController < ApplicationController

    def new
        @deadline = current_user.deadlines.new
    end

    def create
        @deadline = current_user.deadlines.new(params[:deadline].permit(:title, :date, :description))
        if @deadline.save
            redirect_to @deadline
        else
            render 'new'
        end
    end

    def show
        @deadline = Deadline.find(params[:id])
    end

    def edit
        @deadline = current_user.deadlines.find(params[:id])
    end

    def index

        @deadlines = current_user.deadlines.all
        @deadlines = current_user.deadlines.paginate(:page => params[:page], :per_page => 5)
    end

    def update
        @deadline = current_user.deadlines.find(params[:id])

        if @deadline.update(params[:deadline].permit(:title, :date, :description))
            redirect_to @deadline
        else
            render 'edit'
        end
    end

    def destroy
        @deadline = current_user.deadlines.find(params[:id])
        @deadline.destroy

        redirect_to deadlines_path

    end

    private
    def post_params
        params.require(:deadline).permit(:title, :date, :description)
    end

end

截止日期模型:

    class Deadline < ActiveRecord::Base

    validates :title, presence: true,
                length: { minimum: 8 }


    validates :date, presence: true

    validates :description, presence: true,
                length: { maximum: 230 }

   #validates_format_of :date, :with => /\A[0-9]{4}-[0-1][0-9]-[0-3][0-9]\z/, :message => "Enter Date in this format: YYYY-MM-DD" 
    belongs_to :user    

end

2 个答案:

答案 0 :(得分:1)

@deadlines = current_user.deadlines.order(:date)
                         .paginate(:page => params[:page], :per_page => 5)

答案 1 :(得分:1)

您可以使用订购方式

@deadlines = current_user.deadlines.order(:date)

您还可以使用

指定升序或降序
@deadlines = current_user.deadlines.order(date: :asc)  # Ascending
@deadlines = current_user.deadlines.order(date: :desc) # Descending