使用自定义属性而不是表列的 Rails 路由 [英] Rails routing using custom attribute rather than table column

查看:65
本文介绍了使用自定义属性而不是表列的 Rails 路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Rails 4.2,我想使用 attr_accessor 而不是表列创建自定义路由,但我无法让 resource_path 方法工作.

Using Rails 4.2, I want to create a custom route using an attr_accessor rather than a table column, but I can't get the resource_path method to work.

我想要这样的自定义路由:/foos/the-title-parameterized-1(其中1"是id物体).

I want custom route like this: /foos/the-title-parameterized-1 (where "1" is the id of the object).

Foo 模型:

#...
attr_accessor :slug
#dynamically generate a slug:
def slug
  "#{self.title.parameterize[0..200]}-#{self.id}"
end
#...

routes.rb:

get 'foos/:slug' => 'foos#show', :as => 'foo'

foos_controller.rb:

def show
  @foo = Foo.find params[:slug].split("-").last.to_i
end 

在我的 show 视图中,当我使用辅助方法 foo_path 时,它使用对象的 id 而不是 返回路由>slug 像这样:/foos/1.是否可以让这个辅助方法使用访问器方法?我是否偏离了这种方法?

In my show view, when I use helper method foo_path it returns the route using the id of the object rather than the slug like this: /foos/1. Is it possible to get this helper method to use the accessor method? Am I off track with this approach?

我更喜欢使用 Friendly Id 但我不相信它可能不创建 我的模型表中的 slug 列.我不想创建一个列,因为有数百万条记录.

I would prefer to use Friendly Id but I dont believe its possible without creating a slug column in my model table. I dont want to create a column because there are millions of records.

推荐答案

您想要覆盖 to_param 方法 在您的模型中:

You want to override the to_param method in your model:

class Foo < ActiveRecord::Base
  # ...
  def to_param
    slug
  end

  # or
  alias :to_param :slug
end

您可能还想使用 :constraints 选项 在您的路线中,以便只有匹配的网址,例如/-\d+\z/ 匹配.

You may also want to use the :constraints option in your route so that only URLs that match e.g. /-\d+\z/ are matched.

还要记住,使用这种方法,路径 /foos/i-am-not-this-foos-slug-123 将导致与 /foos 相同的记录/i-am-this-foos-slug-123.

Keep in mind also that, using this method, the path /foos/i-am-not-this-foos-slug-123 will lead to the same record as /foos/i-am-this-foos-slug-123.

这篇关于使用自定义属性而不是表列的 Rails 路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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