Rails路由在URL中创建其他信息

时间:2010-05-13 14:25:24

标签: ruby-on-rails url routes

假设我有一个名为'deliver'的模型,并且我使用默认的URL路由:

 # Install the default routes as the lowest priority.
  map.connect ':controller/:action/:id'
  map.connect ':controller/:action/:id.:format'

因此传递URL将是:

http://localhost:3000/deliver/123

我想要解决的是如何使用数据库中的另一个字段来代替ID。

例如。如果我在创建视图中有一个名为'deliverraddress'的字段,我该如何将其放入路径?

所以我可以将这个链接起来:

http://localhost:3000/deliver/deliveraddress

谢谢,

丹尼

2 个答案:

答案 0 :(得分:2)

由于您的评论听起来像是在尝试对网址中的ID进行模糊处理,因此我建议您查看几天前提出的问题。

Obfuscating ids in Rails app

答案 1 :(得分:1)

首先,网址“http://localhost:3000/deliver/123”与默认路由规则匹配。但是,只有在声明了“资源”之后,它才会生成这样一个RESTful URL。

在您的情况下,只需实现Deliver模型的“to_param”方法:

class Deliver < ActiveRecord::Base
  def to_param
    return self.deliveraddress
  end
end

它会通过调用url_for方法生成您想要的网址,例如link_to @deliver

不要忘记确保数据库中有唯一的传递地址,这样您就永远不会找到包含一个地址的重复记录。

之后,您需要更新操作中的finder方法:

def show
  @deliver = Deliver.find_by_deliver_address!(params[:id])
end

希望这个答案有用。