【发布时间】:2010-10-04 06:30:22
【问题描述】:
我遇到了一个小问题...我设置了一个 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
每当我在任何link_to 方法中使用“job_description_path”时,都会将我的网址呈现为类似于“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”。
有什么想法吗?!?
问候,
塞巴斯蒂安
【问题讨论】:
标签: ruby-on-rails map routes link-to