自定义Friendly_id URL

时间:2014-02-18 22:07:17

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

首先,我很抱歉我的英语

我正在使用Friendly_id gem来创建Clean URL并且它工作得很好但是没有像这样的http://localhost:3000/profile/jack-sparo这样的网址我想要一个这样的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

1 个答案:

答案 0 :(得分:0)

如果你的URL中有id的记录,那么你就不需要了 Friendly_id宝石。你需要调整路线。

但也许你会对这样的事情感到满意吗?

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

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

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

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

的网址
http://localhost:3000/profiles/1-john-smith

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

所以

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

将链接到与

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