加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 如何设置url helper方法参数的默认值?

发布时间:2020-12-16 22:11:05 所属栏目:百科 来源:网络整理
导读:我使用语言代码作为前缀,例如www.mydomain.com/en/posts/1. 这是我在routes.rb中所做的: scope ":lang" do resources :postsend 现在我可以轻松使用url助手,例如:post_path(post.id,:lang =:en).问题是我想在cookie中使用一个值作为默认语言.所以我只能
我使用语言代码作为前缀,例如www.mydomain.com/en/posts/1.
这是我在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中

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读