在rails中重命名路由(map,link_to,to_param)

时间:2009-01-29 15:25:43

标签: ruby-on-rails map routes link-to

我有一点问题......我设置了一个用于服务德国网站的rails应用程序。为了利用Rails的内部复数功能,我将所有模型保留为英语(例如模型“JobDescription”)。 现在,如果我打电话给“http://mysite.com/job_descriptions/”,我的所有job_descriptions ....到目前为止都很好。因为我不想在我的网址中使用英文术语“job_descriptions”,所以我将以下内容放入我的路线中.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友好,我想在URL中交换id以获得更加用户友好的slug。因此,我将以下内容放在job_description.rb

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

每当我在任何job_description_path方法中使用“link_to”时,都会将我的网址呈现为“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次调用相当繁琐。我想要的是将“job_description”替换为“german_term”,只要它出现在网址中。

有什么想法吗?!?

问候,

塞巴斯蒂安

2 个答案:

答案 0 :(得分:7)

我认为你需要使用宁静的路线助手来获得你想要的东西。

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

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

希望这有帮助!

答案 1 :(得分:0)

Rails仅使用

def to_params 
end

使用restful路由/链接帮助程序时的URL构建器。我所知道的唯一方法是按照你的方式做的,除非你愿意废弃你的英语链接并用德语完成。在这种情况下,只需删除命名的路由行并更改to_params以使用数据库中的正确名称字段。此时,REST路由应该正常运行。