在rails3上调用方法查看hepler问题
我有两个视图助手,
module Admin::CategoriesHelper
def test
return "a"
end
module CategoriesHelper
def test
return "b"
end
我在views/admin/categories/index.html.erb中调用测试方法
=============================== =========================================
如果我使用 Admin::CategoriesHelper.test 它将抛出如下错误:
NoMethodError in Admin/categories#index
Showing /home/mlzboy/my/b2c2/app/views/admin/categories/index.html.erb where line #32 raised:
undefined method `my_new_admin_category_path' for Admin::CategoriesHelper:Module
Extracted source (around line #32):
29:
30: <br />
31:
32: <%= link_to 'New Category', Admin::CategoriesHelper.my_new_admin_category_path(@parent) %>
则返回 b
而不是 a
如果我更改方法名称(例如 test2 与 CategoryHelper 不一样), 它工作正常
,那么如何解决这个问题,我是rails新手,我想知道为什么会发生这种情况,谢谢
我的routes.rb有问题吗?,我的routes.rb文件如下
namespace :admin do
resources :categories
end
resources :categories
i have two view helper
module Admin::CategoriesHelper
def test
return "a"
end
module CategoriesHelper
def test
return "b"
end
i invoke test method in views/admin/categories/index.html.erb
====================================================================
if i use Admin::CategoriesHelper.test it will throw error like bellows:
NoMethodError in Admin/categories#index
Showing /home/mlzboy/my/b2c2/app/views/admin/categories/index.html.erb where line #32 raised:
undefined method `my_new_admin_category_path' for Admin::CategoriesHelper:Module
Extracted source (around line #32):
29:
30: <br />
31:
32: <%= link_to 'New Category', Admin::CategoriesHelper.my_new_admin_category_path(@parent) %>
it's return b
not a
if i change the method name like test2 didn't have the same with CategoriesHelper
it's work fine
so how to resolve this problem,i newibe in rails,i want to know why this happen,thanks
is there something wrong with my routes.rb?,my routes.rb file is as bellows
namespace :admin do
resources :categories
end
resources :categories
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的
Admin::CategoriesHelper
和CategoriesHelper
均已加载并在您的视图中公开。这意味着最后加载的模块将被执行。为了说明我的观点,您的视图加载如下所示的帮助器:
Helper1
和Helper2
都包含一个方法test
。在这种情况下,当您运行MyView#test
时,它将执行Helper2#test
。Helper1#test
已被覆盖,无法访问。因为 ActionView(或任何负责加载帮助程序的东西)以任意顺序加载帮助程序,所以您遇到了麻烦。
我的解决方案是在命名空间模块中添加方法前缀:
Both your
Admin::CategoriesHelper
andCategoriesHelper
are loaded and exposed in your views. This means that the module that was loaded last will be executed.To illustrate my point, your view loads helpers like this:
Both
Helper1
andHelper2
include a methodtest
. In this case when you runMyView#test
it will executeHelper2#test
.Helper1#test
has been overwritten and cannot be accessed.Because ActionView (or whatever is responsible for loading the helpers) loads helpers in an arbitrary order, you're in trouble.
My solution is to prefix methods in the namespaced module: