Search code examples
ruby-on-railsruby-on-rails-5rails-routing

rails URL rewriting using


How to rewrite below URL

127.0.0.1:3000/article/index?type=1

as

127.0.0.1:3000/article/category/brand

where type 1 is category with name brand.

is it possible using rails?

route.rb

get "article/index"

article_controller.rb

def index
  @article =  Article.find(params[:type])
end

article.rb //model

class Article < ApplicationRecord
  belongs_to :category
end

link to this route

<%= link_to category.name, {:controller => "article", :action => "index", :type => category.id }%>

Solution

  • Rails doesn't provide what you are trying to achieve out of the box. Here I give you some suggestions to get you where you wanted to go.

    1. routes.rb
    get "articles/category/:id" => "articles#index", as: "articles_by_category"
    

    As such nothing wrong with your configuration but not a good practice. Learn more about it here

    1. models/article.rb - leave as is
    2. Use https://github.com/norman/friendly_id Gem. Follow usage guide https://github.com/norman/friendly_id#usage to install and configure it.

    3. models/category.rb

    class Category < ApplicationRecord
      extend FriendlyId
      friendly_id :name, use: :slugged
    
      has_many :articles
    end
    
    1. <%= link_to category.name, articles_by_category_path(category.id) %>
      
    2. article_controller.rb

    def index
      @articles = Category.friendly.find(params[:id]).articles
    end
    

    P.S. the assumption here is there will be multiple articles for given category.