Rails:帖子的自定义URL

时间:2016-07-25 21:05:26

标签: ruby-on-rails content-management-system blogs

在我的rails应用中,我有一个帖子部分,允许用户提交的内容。默认情况下,新帖子的网址约定类似yoursite/posts/8。我想知道是否有人知道是否有可能为用户创建一个自定义URL路由的方法,例如创建一个新帖子,然后有一个带有“自定义URL”的字符串,所以它变成类似{{ 1}}有谁知道怎么会这样做?谢谢!

帖子架构如下所示:

'yoursite/posttopic'.

1 个答案:

答案 0 :(得分:1)

使用friendly_id gem。来自Quick start guide的更新示例:

public partial class ManageController : Controller
{
    private ApplicationSignInManager _signInManager;
    private ApplicationUserManager _userManager;
    private DBContext _dbContext;

    public DBContext DBContext
    {
        get
        {
            return _dbContext ?? HttpContext.GetOwinContext().Get<DBContext>();
        }
        private set
        {
            _dbContext = value;
        }
    }

    // some user profile functions

    [ChildActionOnly]
    public ActionResult SiteErrorBanner()
    {
        var model = new Webapp.Models.SiteErrorModel();
        model.UnresolvedErrors = new List<DataLibrary.site_errors>();
        model.UnresolvedErrors = DBContext.site_errors.Where(error => error.resolved == false).ToList();
        return PartialView(MVC.Shared.Views.ErrorBanner, model);
    }
}

现在你可以使用它:

# edit app/models/post.rb
class Post < ActiveRecord::Base
  extend FriendlyId
  friendly_id :title, use: :slugged
end

Post.create! title: "posttopic"

# Change Post.find to Post.friendly.find in your controller
Post.friendly.find(params[:id])
rails server