In url, how to show name-name instead of id in ruby ​​on rails?

I am using rails 4 and ruby ​​2. I have created a blog part in my rails application. I need to change url on my show page. My problem is I want a title in my url instead of an id. I want http://www.domain.com/articles/blog_title instead of http://www.domain.com/articles/9 . How can i do this? Please share with me if anyone has any idea on this.

My codes:

ArticlesController:

def index
    @articles = Article.all
    @articles = Article.paginate(:page => params[:page], :per_page => 5).order('created_at DESC')
end

def show
  @article = Article.find(params[:id])
end

private

def article_params
  params.require(:article).permit(:title, :body)
end

      

routes.rv

resources :articles

      

+3


source to share


2 answers


There is an amazing gem named for this purpose friendly_id

, https://github.com/norman/friendly_id

In your article model, you just need to add this,

extend FriendlyId
friendly_id :name, use: :slugged

      



There are many other options available, for which you need to check the documentation.

Hope it helps!

+6


source


You can actually override the method to_param

. You don't need to have a stone for this.

If you have a slug column, just put

def to_param
    self.slug.parameterize
end

      



If you want to go with a headline then

def to_param
    self.title.parameterize
end

      

Remember to index the slug or title columns (whichever you are using) to speed up searches.

+4


source







All Articles