Cómo crear URL fáciles de buscar en 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 a http://www.exaple.com/blogs/blog-name Aquí, estoy creando una muestra. Rieles5 aplicación con modelo de publicación para ilustrar cómo funcionará exactamente con las bonitas URL.
Título de la publicación del andamio Rails G: cadena publicada: booleano
correr rieles db:migrar y cree algunas publicaciones de muestra (http://localhost:3000/posts/new) aplicación/modelos/post.rb
def to_param título.parameterize fin
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
migración de rieles g AddSlugToPosts slug:cadena
Abra el archivo de migración mencionado anteriormente y agregue un índice uniq a ese sulg. Slug debe ser único.
clase AddSlugToPosts < ActiveRecord::Migration[5.0] def cambiar add_column :posts, :slug, :string add_index :posts, :slug, único: verdadero fin fin
correr base de datos:migrar 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
Ahora está funcionando como se esperaba con las bonitas URL. ¿Qué pasa si dos registros tienen la misma URL ya que ambos registros tienen el mismo nombre? Porque .find_by siempre recupera el primer registro. Para resolver esto, antes de guardar el slug, podemos combinar la identificación del registro con el slug como se menciona a continuación:
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. Gema amigable_id(Rails 5) Add the latest gem from rubygem web to the gemfile and run bundle
gema 'friendly_id', '~> 5.1'
los rieles generan amigable_id
El comando anterior genera un archivo inicializador y un archivo de migración.
ejecutar db:migrar
Cree algunos registros y cambie nuestro método set_post a la forma que se menciona a continuación. Todos los registros antiguos deben regenerarse, en caso de que tenga alguno.
def set_post Post.friendly.find("Joe Schmoe".parameterize) fin
aplicación/modelos/post.rb
extender FriendlyId friendly_id :slug_candidates, uso: [:slugged, :finders, :history] def slug_candidates [ :title, [:title, :id] ] fin
Agregar atributo slug al modelo de publicación
rieles g AddSlugToPosts slug:cadena
add_column: publicaciones,: slug,: cadena
add_index: publicaciones,: slug, único: verdadero
Actualizando el título de la publicación Slug se actualizará automáticamente cuando actualice el atributo del título. Pero no es una buena práctica actualizar los slugs con demasiada frecuencia. La aplicación puede generar errores al hacer clic en cualquiera de las URL marcadas porque cualquiera puede tener marcadores antiguos. Necesitamos evitar esto agregando el símbolo de historial a la opción de uso en su modelo de publicación.
def slug_candidates [ :título, [:título, :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.
Artículos Relacionados

Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *

es_ESSpanish