URL 中的 Rails slugs - 使用 Active Record Model Post 的 Title 属性而不是 ID [英] Rails slugs in URL - using Active Record Model Post's Title attribute instead of ID

查看:28
本文介绍了URL 中的 Rails slugs - 使用 Active Record Model Post 的 Title 属性而不是 ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直试图让我的 Rails 创建 URL 以通过在 URL 中使用它们的标题而不是它们的 ID 来显示记录,例如:

I've been trying to make my Rails create URLs to show records by using their title instead of their ID in URL such as:

/posts/a-post-about-rockets

/posts/a-post-about-rockets

根据在线教程,我执行了以下操作:

Following a tutorial online I did the following:

因为 ID 不再在 URL 中,所以我们必须稍微更改代码.

Because the ID is no longer in the URL, we have to change the code a bit.

class Post < ActiveRecord::Base
  before_create :create_slug

  def to_param
    slug
  end

  def create_slug
    self.slug = self.title.parameterize
  end
end

创建帖子时,标题的 URL 友好版本存储在数据库中的 slug 列中.

When a post is created, the URL friendly version of the title is stored in the database, in the slug column.

我们还必须更新查找结果以使用 slug 列而不是使用 ID 查找记录.

We also have to update the finds to find records using the slug column instead of using the ID.

class ProjectsController < ApplicationController
  def show
    @project = Project.find_by_slug!(params[:id])
  end
end

<小时>

在这一点上,除了显示记录外,它似乎可以工作,因为 find_by_slug!还不存在.


At this point it seems to work except showing a record, because find_by_slug! doesnt exist yet.

我是一个极端的新手 - 我应该在哪里定义它?

I'm an extreme newb - where should I be defining it?

推荐答案

find_by_foo 不是您需要定义的.只要您有一个名为foo"的列,ActiveRecord 就会为您处理.像您一样添加感叹号将导致在未找到任何记录时抛出异常,而如果不使用感叹号则返回 nil 而没有异常.

find_by_foo is not something that you need to define. ActiveRecord will take of it for you, as long as you have a column named "foo". Adding an exclamation point like you did will cause an exception to be thrown if no record is found, as opposed to returning nil without the exception if you don't use the exclamation point.

至于您的具体问题,您已将 slug 添加到 Post,但您正在尝试在 Project 上进行搜索.

As for your specific issue, you added your slug to Post, but you're trying to search on Project.

这篇关于URL 中的 Rails slugs - 使用 Active Record Model Post 的 Title 属性而不是 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆