具有相同方法名称的多个Rails助手

Kyl*_*cot 5 ruby-on-rails ruby-on-rails-3

我有两个不同的帮助文件(photos_helper和comments_helper)w /有一个名为的方法actions_for.如何显式调用我需要的辅助方法?我知道我可以重命名其中一个,但我更愿意让它们保持不变.我尝试过,PhotosHelper::actions_for但似乎没有用.

Mar*_*rth 7

在Rails 3中,所有帮助程序总是(在Rails 3.1中存在一个补丁,以便有选择地再次允许帮助程序).幕后发生了什么:

class YourView
  include ApplicationHelper
  include UserHelper
  include ProjectHelper

  ...
end
Run Code Online (Sandbox Code Playgroud)

因此,根据Rails包含它们的顺序,actions_for将使用您的任何方法.你无法明确选择其中一个.

如果您必须明确调用ProjectHelper.action_for,您也可以命名您的方法project_action_for- 最简单的解决方案.


Sal*_*lil 6

让他们两个 Class Method

module LoginsHelper
  def self.your_method_name
    "LoginsHelper"
  end
end
Run Code Online (Sandbox Code Playgroud)

module UsersHelper
  def self.your_method_name
    "UsersHelper"
  end
end
Run Code Online (Sandbox Code Playgroud)

然后在视图中

   LoginsHelper.your_method_name #Gives 'LoginsHelper'
Run Code Online (Sandbox Code Playgroud)

   UsersHelper.your_method_name #Gives 'UsersHelper'
Run Code Online (Sandbox Code Playgroud)

  • 但是,这不允许访问其中任何其他"常规"ActionView :: Helper方法,如link_to,_url,image_tag. (2认同)