【问题标题】:Customizing Friendly_id URL自定义 Friendly_id URL
【发布时间】:2014-03-18 22:59:54
【问题描述】:

首先对不起我的英语

我正在使用 Friendly_id gem 来创建 Clean URL,它工作得很好,但是我想要一个像 http://localhost:3000/profile/jack-sparo 这样的 URL,而不是像这样的 URL http://localhost:3000/profile/1/jack-sparo其中 1 是 user_id,那么我该怎么做呢?

这是我的配置/路线

  get "profiles/show" 

  get '/profile/:id' => 'profiles#show', :as => :profile
  get 'profiles' => 'profiles#index'

这是我的个人资料控制器

  def show
    @user= User.find_by_slug(params[:id])
    if @user
        @posts= Post.all
        render action: :show
    else
        render file: 'public/404', status: 404, formats: [:html]
    end
  end

【问题讨论】:

  • 发布你的 config/routes.rb 我可以给你确切的代码,不过这取决于你当前的路线。

标签: ruby-on-rails ruby friendly-url friendly-id


【解决方案1】:

如果您在 URL 中有记录的id,则不需要 Friendly_id 宝石。您需要调整路线。

但也许你会喜欢这样的东西?

http://localhost:3000/profiles/1-john-smith

如果是这样,您需要覆盖User 模型中的to_param 方法,例如 这个:

class User < ActiveRecord::Base
  def to_param
    "#{id}-#{name}".parameterize
  end
end

现在profile_path(profile) 助手将生成类似的 URL

http://localhost:3000/profiles/1-john-smith

并且,通过这个请求,控制器中的 User.find(params[:id]) 将找到 ID 为 1 的个人资料并删除 URL 中的所有其他内容。

所以

http://localhost:3000/profiles/1-mojombo-smith

将链接到与

相同的个人资料
http://localhost:3000/profiles/1-john-smith

【讨论】:

  • 这种方法的缺点是我仍然可以使用 user_id 访问配置文件,例如 profiles/1 或 profiles/1-somes-words
  • 否则,您必须将名称从 URL 解析为数据库友好格式,才能同时使用 first_namelast_nameid 进行搜索。看起来有点过于复杂了。
猜你喜欢
  • 1970-01-01
  • 2014-03-30
  • 1970-01-01
  • 1970-01-01
  • 2023-01-27
  • 2022-07-13
  • 1970-01-01
  • 1970-01-01
  • 2021-05-20
相关资源
最近更新 更多