【问题标题】:changing id/URL slug in rails 3 app using mongoid使用 mongoid 在 rails 3 应用程序中更改 id/URL slug
【发布时间】:2012-01-17 13:40:20
【问题描述】:

目前在我的 rails 应用程序中,记录位于以下 URL:

http://www.mysite.com/items/fecffe6aa299a6050274ed22

但我希望他们去类似的地方:

http://www.mysite.com/items/item-title-here

我有什么想法可以做到这一点吗?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 mongodb mongoid


    【解决方案1】:

    我推荐使用mongoid_slug gem:它允许您基于 Mongoid 模型中的一个或多个字段生成 URL slug 或永久链接。

    这是它们的用法示例:

    ## Set up a slug:
    class Book
        include Mongoid::Document
        include Mongoid::Slug
        field :title
        slug :title
    end
    
    ## Find a record by its slug:
    # GET /books/a-thousand-plateaus
    book = Book.find_by_slug params[:book_id]
    

    【讨论】:

      【解决方案2】:

      查看此 railscast:FriendlyId

      不过,它是用于 ActiveRecord,而不是 Mongoid。但你仍然可以从中得到灵感。

      【讨论】:

      • 啊,抱歉,没注意到标签。但是,您仍然可以了解这个概念:-)
      • mongo id get 的处理方式与序数 id 相同。
      【解决方案3】:

      只需修改“显示”功能

      例如

      默认显示

      item= Item.where({name=>params[:id]}).first
      do something...
      

      结束

      只要把函数从你自己的id中获取一个对象....

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-03-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多