自动将参数附加到* _url或* _path方法(Rails) [英] Automatically append parameters to *_url or *_path methods (Rails)
问题描述
我有一组与我的一个控制器相关的视图,因此我希望对*_path
或*_url
的任何调用都可以附加一组参数.
I have a particular set of views relating to one of my controllers, whereby I want any call to *_path
or *_url
to append a set of parameters.
是否有一些我可以替代的魔术方法可以让我做到这一点?我不知道*_path
或*_url
方法在Rails代码中的哪儿都可以处理.
Is there some magic method I can override that will let me do this? I have no idea where in the Rails code the *_path
or *_url
methods are even handled.
为清楚起见进行我正在寻找一种方法来执行此操作,从而不必在需要进行此操作的每个视图中都修改每个链接.我不希望每个接触这组视图的编码人员都必须记住将参数添加到他们添加到页面的每个链接中.相同的参数应自动附加.我认为对*_url
或*_path
的更改称为失败.同样,必须重写每个*_url
或*_path
调用被视为失败,因为每当添加/删除新链接时,都必须添加/删除新方法.
Edit for clarity: I'm looking for a way to do this such that I don't have to modify every link in every view where this needs to occur. I don't want every coder who touches this set of views to have to remember to append a parameter to every link they add to the page. The same parameter should be appended automatically. I consider a change to the *_url
or *_path
call a failure. Similarly, having to override every *_url
or *_path
call is considered a failure since a new method would have to be added/removed whenever a new link is added/removed.
推荐答案
Thanks to Samuel's answer, I was able to create a final working solution via a new helper, which I've included below.
module ExampleHelper
def url_for(options={})
options = case options
when String
uri = Addressable::URI.new
uri.query_values = @hash_of_additional_params
options + (options.index('?').nil? ? '?' : '&') + uri.query
when Hash
options.reverse_merge(@hash_of_additional_params)
else
options
end
super
end
end
这篇关于自动将参数附加到* _url或* _path方法(Rails)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!