如何绕过default_url_options? [英] How to bypass default_url_options?

查看:166
本文介绍了如何绕过default_url_options?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的上一个Rails项目中,我必须覆盖application_controller.rb中的default_url_options,以始终通过每个请求传递参数,如下所示:

In my last Rails project I had to overwrite default_url_options in application_controller.rb to always pass a param through every request, like this:

def default_url_options 
  { :my_default_param => my_param_value }
end  

现在,每个url帮助器都会在每个生成的url的末尾附加一个my_default_param. 例如,user_url(@current_user)生成如下网址:

Now every url helper attaches a my_default_param at the end of every generated url. For instance user_url(@current_user) generates a url like:

http://www.example.com/users/1?&my_default_param=my_param_value 

但是有时我需要生成不带my_default_param的URL .有什么我可以传递给url帮助器的选项,以便user_url(@current_user, some_option: some_option_value)仅返回:

But sometimes I need to generate the url without my_default_param. Is there some option I can pass to the url helper so that user_url(@current_user, some_option: some_option_value) will return only:

http://www.example.com/users/1?&my_default_param=my_param_value

?

PN:我已经尝试使用:overwrite_params=> { },但是它不起作用,可能是因为它是在default_url_options之前进行评估的.

PN: I already tried with :overwrite_params=> { } but it doesn't work, probably because it's evaluated before default_url_options.

如果没有,是否还有另一种方法来获取未附加my_default_param的@current_user URL?

谢谢.

推荐答案

default_url_options 具有一个参数 options,您可以根据需要使用它:

default_url_options has one param options which you could use as you wish:

def default_url_options( options = {} )

  use_defaults = options.delete( :use_defaults )

  if use_defaults
    { :my_default_param => 'my_param_value' }
  else
    {}
  end

end

或者您可以颠倒逻辑:

def default_url_options( options = {} )

  ignore_defaults = options.delete( :ignore_defaults )

  if ignore_defaults
    {}
  else
    { :my_default_param => 'my_param_value' }
  end

end

这篇关于如何绕过default_url_options?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆