我遇到了一个小问题...我设置了一个为德国网站提供服务的 Rails 应用程序。为了利用 Rails 的内部多元化功能,我将所有模型都保留为英文(例如模型“JobDescription
”)。
现在,如果我调用“http://mysite.com/job_descriptions/
”,我会得到我所有的job_descriptions
....到目前为止,还不错。因为我不想在我的 url 中出现英文术语“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
每当我在任何 link_to
方法中使用“job_description_path
”时,都会将我的 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
调用是相当乏味的。我想要的是将“job_description
”替换为“german_term
”,只要它出现在 URL 中。
有什么想法吗?!?
问候,
塞巴斯蒂安
最佳答案
我认为您将需要使用 restful 路由助手来获得您想要的东西。
在那种情况下,不需要太多重构(假设您已将 JobDescriptions 映射为资源)。保持你的 to_param 不变,并将你的 JobDescriptions 路由更改为如下所示:
map.resources :job_descriptions, :as => 'german_term'
希望这对您有所帮助!
关于ruby-on-rails - 在 rails 中重命名路线(map、link_to、to_param),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/492042/