如何为每个帖子生成短网址?

时间:2014-03-21 22:43:40

标签: ruby-on-rails url-shortener

我是rails的新手,我有一个应用程序允许用户创建截止日期,就像为博客创建帖子一样,然后希望能够为该截止日期创建一个简短的URL以供用户共享?我将如何创建像bit.ly这样的简短网址。

  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

   #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

1 个答案:

答案 0 :(得分:2)

您可以使用 shortener gem ,这样可以轻松为Rails应用程序创建缩短的URL。