0

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 }%>
2
  • Share your routes.rb, article and category model, and view code as well. Commented Mar 31, 2020 at 7:13
  • please check updated code above Commented Mar 31, 2020 at 7:28

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.