我使用语言代码作为前缀,例如www.mydomain.com/en/posts/1.
这是我在routes.rb中所做的:
这是我在routes.rb中所做的:
scope ":lang" do resources :posts end
现在我可以轻松使用url助手,例如:post_path(post.id,:lang =>:en).问题是我想在cookie中使用一个值作为默认语言.所以我只能写post_path(post.id).
有没有办法如何在url helpers中设置参数的默认值?我找不到网址助手的源代码 – 有人能指出我正确的方向吗?
另一种方式:我已经尝试在routes.rb中设置它,但它仅在启动时评估,这对我不起作用:
scope ":lang",:defaults => { :lang => lambda { "en" } } do resources :posts end
解决方法
这是我头脑中的编码,所以不能保证,但在初始化器中尝试一下:
module MyRoutingStuff alias :original_url_for :url_for def url_for(options = {}) options[:lang] = :en unless options[:lang] # whatever code you want to set your default original_url_for end end ActionDispatch::Routing::UrlFor.send(:include,MyRoutingStuff)
或直的猴子补丁……
module ActionDispatch module Routing module UrlFor alias :original_url_for :url_for def url_for(options = {}) options[:lang] = :en unless options[:lang] # whatever code you want to set your default original_url_for end end end end
url_for的代码位于Rails 3.0.7中的actionpack / lib / routing / url_for.rb中
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。