Comment créer des URL conviviales pour la recherche dans Rails

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 à http://www.exaple.com/blogs/blog-name Ici, je crée un échantillon Rails5 application avec modèle de publication pour illustrer exactement comment cela va fonctionner avec les jolies URL.
titre du message d'échafaudage Rails G : chaîne publiée : booléen
courir base de données rails: migrer et créez quelques exemples de publications (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: chaîne
Ouvrez le fichier de migration mentionné ci-dessus et ajoutez un index uniq à ce sulg. Slug doit être unique.
class AddSlugToPosts < ActiveRecord::Migration[5.0] def change add_column :posts, :slug, :string add_index :posts, :slug, unique : true end end
courir base de données: migrer 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]) fin
Maintenant, cela fonctionne comme prévu avec les jolies URL. Que se passe-t-il si deux enregistrements ont la même URL puisque ces deux enregistrements portent le même nom. Parce que .find_by récupère toujours le premier enregistrement. Pour résoudre ce problème, avant de sauvegarder le slug, nous pouvons combiner l'identifiant de l'enregistrement avec le slug de la manière mentionnée ci-dessous :
def add_slug "#{id}-#{title.parameterize}" fin
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. Joyau Friendly_id(Rails 5) Add the latest gem from rubygem web to the gemfile and run bundle
gemme 'friendly_id', '~> 5.1'
les rails génèrent un friendly_id
La commande ci-dessus génère un fichier d'initialisation et un fichier de migration.
exécuter db: migrer
Créez des enregistrements et modifiez notre méthode set_post comme indiqué ci-dessous. Tous les anciens enregistrements doivent être régénérés, au cas où vous en auriez.
def set_post Post.friendly.find("Joe Schmoe".parameterize) end
app/models/post.rb
extend FriendlyId friendly_id :slug_candidates, utilisez : [:slugged, :finders, :history] def slug_candidates [ :title, [:title, :id] ] end
Ajouter l'attribut slug au modèle Post
rails g AddSlugToPosts slug: chaîne
add_column :posts, :slug, :string
add_index :posts, :slug, unique : vrai
Mise à jour du titre du message Slug se mettra à jour automatiquement lorsque vous mettrez à jour l'attribut title. Mais ce n'est pas une bonne pratique de mettre à jour les slugs trop fréquemment. L'application peut générer des erreurs en cliquant sur l'une des URL mises en signet, car n'importe qui peut avoir d'anciens signets. Nous devons éviter cela en ajoutant un symbole d'historique à l'option d'utilisation dans votre modèle Post.
def slug_candidates [ :title, [:title, :id] ] fin
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.
Articles Similaires

Laissez un commentaire

Votre adresse de messagerie ne sera pas publiée. Les champs obligatoires sont indiqués avec *

fr_FRFrench