2

我有一个小问题...我设置了一个为德国网站提供服务的 Rails 应用程序。为了利用 Rails 的内部复数功能,我将所有模型都保留为英文(例如模型“ JobDescription”)。现在,如果我打电话给“ http://mysite.com/job_descriptions/”,我会得到我所有的job_descriptions……到目前为止,太好了。因为我不想job_descriptions在我的网址中使用英文术语“”,所以我将以下内容放入了我的 routes.rb

map.german_term '/german_term', :controller => 'job_descriptions', :action => 'index'
map.german_term '/german_term/:id', :controller => 'job_descriptions', :action => 'show'

如果我打电话给“ http://mysite.com/german_term/”或“ http://mysite.com/german_term/283”我得到所有我的job_descriptions,这很好。

但是,为了使 URL 对 SEO 更友好,我想将 id 换成 URL 中对用户更友好的 slug。因此,我将以下内容放入我的job_description.rb

def to_param
"#{id}-#{name.gsub(/[^a-z0-9]+/i, '-')}"
end

每当我job_description_path在任何link_to方法中使用“”时,都会将我的 URL 呈现为“ http://mysite/job_descriptions/13-my-job-description-title ”之类的东西。

但是,这就是我卡住的地方,我想得到“ http://mysite/german_term/13-my-job-description-title”。我已经尝试在 link_to 代码中将“ job_description_path”与“ german_term_path”交换,但这只会生成“ http://mysite/german_term/13”。显然,to_param不叫。我发现的一种解决方法是建立链接:

<%= link_to job_description.name, german_term_path(job_description.to_param) %>

但是更改link_to我的代码中的所有调用是相当乏味的。我想要的是在 URL 中出现时将“ job_description”替换为“”。german_term

有什么想法吗?!?

问候,

塞巴斯蒂安

4

2 回答 2

7

我认为您将需要使用 restful 路线助手来获得您想要的东西。

在这种情况下,不需要太多重构(假设您已将 JobDescriptions 映射为资源)。保留您的 to_param 并将您的 JobDescriptions 路由更改为以下内容:

map.resources :job_descriptions, :as => 'german_term'

希望这可以帮助!

于 2009-01-29T15:54:44.180 回答
0

Rails 只使用

def to_params 
end

当您使用宁静的路由/链接助手时的 URL 构建器。我知道的唯一方法是像你做的那样做,除非你愿意放弃你的英语链接并用德语做这一切。在这种情况下,只需去掉命名的路线并更改 to_params 以使用数据库中的正确名称字段。此时,REST 路由应该正确运行。

于 2009-01-29T15:46:12.077 回答