【问题标题】:Use Slug and id in URL with Friendly_Id Gem通过 Friendly_Id Gem 在 URL 中使用 Slug 和 id
【发布时间】:2014-03-19 02:46:30
【问题描述】:

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

【问题讨论】:

    标签: ruby-on-rails ruby routes url-routing friendly-url


    【解决方案1】:

    我认为这是可行的:

    # change in config/routes.rb
    get '/profile/:id(/:username)' => 'profiles#show', :as => :profile
    
    # change in app/controllers/profile_controller.rb
    @user= User.find(params[:id])
    
    # add to app/models/user.rb
    def to_param
      "#{id}/#{username}"
    end
    

    其中username 是friendly_id 用来生成slug 的任何东西

    【讨论】:

      猜你喜欢
      • 2015-07-30
      • 1970-01-01
      • 1970-01-01
      • 2018-03-22
      • 2015-12-27
      • 1970-01-01
      • 2017-05-30
      • 2014-11-20
      • 2014-02-13
      相关资源
      最近更新 更多