ruby-on-rails – 如何全局覆盖rails url helper?

我需要在foo_path中添加一个简单的更改,所以我这样做了:
module ApplicationHelper
  # [...]

  def foo_path(foo,options = {})
    options.merge!(bar: foo.some_attribute)
    super
  end

  # [...]
end

现在,这在从视图调用时起作用,但是当从控制器调用时,使用没有添加的原始变体.

如何覆盖应用程序的相应帮助程序(_path / _url)?

解决方法

我认为最简单的方法自定义routes.rb文件(至少对于静态认参数).文件http://guides.rubyonrails.org/routing.html#customizing-resourceful-routes

认参数示例:

get "/foo(/:bar)" => "my_controller#index",defaults: { bar: "my_default" }

认参数值示例范围:

scope '/(:rec_type)',defaults: { rec_type: 'mammo' },rec_type: /mammo|face/ do
  resources :patients
end

其他选项(用于动态限制):

高级路由约束:

如果您需要更高级/动态限制,请查看本指南:http://guides.rubyonrails.org/routing.html#advanced-constraints.

覆盖default_url_options:

此外,您可以覆盖default_url_options方法以使用路径助手自动添加一些属性(参数):http://guides.rubyonrails.org/action_controller_overview.html#default-url-options.

You can set global default parameters for URL generation by defining a method called default_url_options in your controller. Such a method must return a hash with the desired defaults,whose keys must be symbols:

class ApplicationController < ActionController::Base
  def default_url_options(options = {})
    if action_name == 'foo' # or other conditions
      options[:bar] = 'your_defaults' # add here your default attributes
    end

    options
  end
end

覆盖to_param:

Rails路由系统在模型上调用to_param以获取:id占位符的值. ActiveRecord :: Base#to_param返回模型的id,但您可以在模型中重新定义该方法.例如,给定:

class Product < ActiveRecord::Base
  def to_param
    "#{id}-#{title}"
  end
end

这会产生:/ products / 254-Foo

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...