自动将参数附加到* _url或* _path方法(Rails)
我有一组特定的视图与我的一个控制器有关,我希望任何调用*_path
或*_url
来附加一组参数。
是否有一些我可以覆盖的魔术方法让我这样做? 我不知道在Rails代码中甚至处理了*_path
或*_url
方法。
编辑为清晰起见:我正在寻找一种方法来做到这一点,这样我就不必修改每个需要发生的视图中的每个链接。 我不希望每个触及这组视图的编码器都必须记住在他们添加到页面的每个链接上附加一个参数。 应自动附加相同的参数。 我认为对*_url
或*_path
的更改调用失败。 同样,必须覆盖每个*_url
或*_path
调用都被视为失败,因为每当添加/删除新链接时都必须添加/删除新方法。
您可以通过覆盖url_for
来完成此操作,因为所有路由方法都会调用它。
module ApplicationHelper def url_for(options = {}) options.reverse_merge!(@extra_url_for_options) if @extra_url_for_options super end end
现在您需要做的就是使用before_filter
将@extra_url_for_options
设置为哈希以强制所有URL。
class MyController < ApplicationController before_filter do { @extra_url_for_options = { :format => 'html' } } end
请注意,这将强制所有链接使用额外选项。
感谢Samuel的回答 ,我能够通过一个新助手创建一个最终的工作解决方案,我已经在下面提到了。
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
您可以尝试使用with_options方法。 在你看来,你可以做类似的事情
<% with_options :my_param => "my_value" do |append| -%> <%= append.users_path(1) %> <% end %>
假设你当然有users_path。 my_param = value将附加到url
你可以做一个帮助方法:
def my_path(p) "#{p}_path all the parameters I want to append" end
并在视图中使用
<%= eval(my_path(whatever)) %>
Eval为您提供动态范围,因此您的视图中可用的每个变量都可以在帮助程序中使用。 如果您的参数是常量,您可以摆脱eval调用。