Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In url, how to show title-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 app. I need to change the url in my show page. My problem is , I want title in my url instead of 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 any one has any idea about 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
like image 414
Priyank Dey Avatar asked Dec 11 '22 22:12

Priyank Dey


1 Answers

Actually you can override to_param method. You don't need to have any gem for that.

If you have slug column then just put

def to_param
    self.slug.parameterize
end

If you want to go with title then

def to_param
    self.title.parameterize
end

Remember to index the slug or the title column (whichever you use) to make searching faster.

like image 113
Nitin Satish Salunke Avatar answered Apr 30 '23 23:04

Nitin Satish Salunke