Display IDs in your URLs can be terrible and wasteful for SEO. In this blog entry, I will demonstrate to you how you can utilize slugs to make your URLs more relevant to the page content. In the first place, we will utilize an implicit arrangement (superseding the to_param strategy) to change the URLs and a while later, we will utilize a gem called friendly_id to produce slugs and keep up a past filled with these slugs. So that search engines index your web pages.
For example: http://www.exaple.com/blogs/1 till http://www.exaple.com/blogs/blog-name
Här skapar jag ett prov Räls5 app med inläggsmodell för att illustrera exakt hur det kommer att fungera med de vackra webbadresserna.
skenor g ställningspost title:string publicerad:boolean
springa skenor db:migrera
och skapa några exempelinlägg (http://localhost:3000/posts/new)
app/models/post.rb
def to_param title.parameterize end
All the links will be changed to pretty URLs once you add the above method to your model. Please check on index page where it lists all the posts. However, when you click on that it will show you error page.
Post.find method cannot find the record with id which we are passing in URL. We need to create slugs for the above posts in our db for that model.
Let’s add migration file for the slug
rails g migration AddSlugToPosts slug:string
Öppna den ovan nämnda migreringsfilen och lägg till uniq index till den sulg. Slug måste vara unik.
class AddSlugToPosts < ActiveRecord::Migration[5.0] def change add_column :posts, :slug, :string add_index :posts, :slug, unique: true end end
springa db:migrera
Now, we have to change our show action db query to find_by instead of find method. Because we need to fetch the results based on slug.
Change our set_post method to
def set_post Post.find_by_slug(params[:id]) slut
Nu fungerar det som förväntat med de vackra webbadresserna. Vad händer om två poster har samma URL eftersom båda dessa poster har samma namn. Eftersom .find_by alltid hämtar den första posten. För att lösa detta, innan vi sparar slug, kan vi kombinera post-id med slug så som det nämns nedan:
def add_slug "#{id}-#{title.parameterize}" slut
So, it will generate like “1-blog-name”. We have a gem called friendly_gem to simply take care of all the above-mentioned scenarios.
Feel free to remove the above mentione code from the sample app because everything is managed by the gem.
Friendly_id pärla(Rails 5)
Add the latest gem from rubygem web to the gemfile and run bundle
gem 'friendly_id', '~> 5.1'
rails genererar friendly_id
Kommandot ovan genererar en initialiseringsfil och en migreringsfil.
kör db:migrate
Skapa några poster och ändra vår set_post-metod till det sätt som nämns nedan. Alla gamla poster måste återskapas, om du har några.
def set_post Post.friendly.find("Joe Schmoe".parameterize) slut
Uppdaterar inläggets rubrik
Slug uppdateras automatiskt när du uppdaterar title-attributet. Men det är inte en bra praxis att uppdatera sniglarna för ofta. Applikationen kan skapa fel när du klickar på någon av de bokmärkta webbadresserna eftersom någon kan ha gamla bokmärken. Vi måste förhindra detta genom att lägga till historiksymbol till användningsalternativet i din Post-modell.
def slug_candidates [ :titel, [:titel, :id] ] slut
slug_candidates feature was added in friendlyId 5. It allows us to tell the friendly id gem, what needs to be done in case of duplicate slugs.
The code mentioned above advises FriendlyId that it needs to utilize the slug_candidates technique to make the slug uniq. It will attempt the rundown right from the beginning to the end, so in the case above, it will attempt to produce the slug first utilizing the title, and afterwards, if a post by that title already exists, it will attempt to fix the ID again.
Slugs are the primary things read by search engines. That ought to, as of now, give you an idea on how essential they are. To utilize a slug, first add the slug alternative to the friendly_id assistant in the Post Model.
Vi använder cookies på vår webbplats för att ge dig den mest relevanta upplevelsen genom att komma ihåg dina preferenser och upprepade besök. Genom att klicka på "ACCEPTERA ALLA" samtycker du till användningen av ALLA cookies. Du kan dock besöka "Cookie-inställningar" för att ge ett kontrollerat samtycke.
Denna webbplats använder cookies för att förbättra din upplevelse när du navigerar genom webbplatsen. Av dessa lagras de cookies som kategoriseras som nödvändiga i din webbläsare eftersom de är nödvändiga för att de grundläggande funktionerna på webbplatsen ska fungera. Vi använder även tredjepartscookies som hjälper oss att analysera och förstå hur du använder denna webbplats. Dessa cookies kommer endast att lagras i din webbläsare med ditt samtycke. Du har också möjlighet att välja bort dessa cookies. Men att välja bort vissa av dessa cookies kan påverka din surfupplevelse.
Nödvändiga cookies är absolut nödvändiga för att webbplatsen ska fungera korrekt. Dessa cookies säkerställer grundläggande funktioner och säkerhetsfunktioner på webbplatsen, anonymt.
Kaka
Varaktighet
Beskrivning
cookielawinfo-checkbox-analytics
11 månader
Denna cookie ställs in av GDPR Cookie Consent-plugin. Cookien används för att lagra användarens samtycke för cookies i kategorin "Analytics".
cookielawinfo-checkbox-functional
11 månader
Cookien sätts av GDPR-cookie-samtycke för att registrera användarens samtycke för cookies i kategorin "Funktionell".
cookielawinfo-checkbox-necessary
11 månader
Denna cookie ställs in av GDPR Cookie Consent-plugin. Cookies används för att lagra användarens samtycke för cookies i kategorin "Nödvändigt".
cookielawinfo-checkbox-others
11 månader
Denna cookie ställs in av GDPR Cookie Consent-plugin. Cookien används för att lagra användarens samtycke för cookies i kategorin "Övrigt.
cookielawinfo-checkbox-performance
11 månader
Denna cookie ställs in av GDPR Cookie Consent-plugin. Cookien används för att lagra användarens samtycke för cookies i kategorin "Prestanda".
viewed_cookie_policy
11 månader
Cookien ställs in av GDPR Cookie Consent-plugin och används för att lagra om användaren har samtyckt till användningen av cookies eller inte. Den lagrar inga personuppgifter.
Funktionella cookies hjälper till att utföra vissa funktioner som att dela innehållet på webbplatsen på sociala medieplattformar, samla in feedback och andra tredjepartsfunktioner.
Prestandacookies används för att förstå och analysera webbplatsens nyckelprestandaindex, vilket hjälper till att leverera en bättre användarupplevelse för besökarna.
Analytiska cookies används för att förstå hur besökare interagerar med webbplatsen. Dessa cookies hjälper till att ge information om mätvärden för antalet besökare, avvisningsfrekvens, trafikkälla, etc.
Annonscookies används för att ge besökarna relevanta annonser och marknadsföringskampanjer. Dessa cookies spårar besökare över webbplatser och samlar in information för att tillhandahålla anpassade annonser.