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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With