Search code examples
ruby-on-railsslugfriendly-id

Friendly_id and two slug start from root


I have two models - Post and Page and their both have a path starting from the first slash. For example:

  1. domain.com/first-slug - it's Post
  2. domain.com/second-slug - it's Page

I can create controller, as ContentController and process slug like this:

class ContentsController < ApplicationController
  def show
    @page = Page.find_by(slug: params[:id])
    @post = Post.find(params[:id]) unless @page
  end
end

but I have some problem with gems, which use controller_name method for define model class.

Second solution, when I use PageController and PostController and routes as:

get '/*id', to: 'pages#show', as: :page
get '/*id', to: 'posts#show', as: :post

an infinite cycle occurs of course

Are there any other ways to solve this non-standard approach?


Solution

  • Of course, I must use constraints in the paths. For example:

    get '/*id', to: 'posts#show', as: :post, constraints: { id: /\d{4}\/\d{2}\/\d{2}\/\w.+/ }
    get '/*id', to: 'pages#show', as: :page