2015-04-19 66 views
1

我正面临以下问题:在我的应用程序中,我使用引擎。假设我有一个商店引擎。在该商店引擎中,我有两个控制器:carts_controller和products_controller及其帮助器:carts_helper和products_helper。在rails中查看辅助方法的未定义方法错误引擎

现在在我的views/shop/products/index.html.erb视图中,我尝试调用在helpers/shop/carts_helper.rb中定义的cart_action方法。但是,不幸的是,当我这样做时,我得到了一个undefined method `cart_action' for #<#<Class:0x007fb3627af090>:0x007fb3627aab08>。当我在helpers/shop/products_helper.rb中放置相同的方法时,我没有收到此消息,该方法正常工作....为什么我不能使用carts_helper中的方法,但是可以使用products_helper中的方法吗?在普通的rails应用程序中,我可以在任何视图中使用任何帮助器方法,对吗?

它可能必须做一些与命名空间即辅助文件不在helpershelpers/shop然而this helps prevent conflicts with helpers from other engines or apps...

module Shop 
    module CartsHelper 
     def cart_action(package_id) 
     #some code 
     end 
    end 
end 

如何调用它shop/products/index.html.erb

<%= cart_action(package['id']) %> 

莫非有与我从我的主应用程序继承我的applications_controller功能的事实?:

class Shop::ApplicationController < ApplicationController 
end 

代替

module Shop 
    class ApplicationController < ActionController::Base 
    end 
end 

FWIW我对这个引擎的路线是这样的:

Shop::Engine.routes.draw do 
    resources :products, only: [:index] 
    # shopping cart 
    resource :cart, only: [:show] do 
     put 'add/:package_id', to: 'carts#add', as: :add_to 
     put 'remove/:package_id', to: 'carts#remove', as: :remove_from 
    end 

end 

感谢您的帮助提前!

注意:我不想在我的主应用程序中使用我的帮助器方法,而只是在同一引擎中的另一个视图中使用我的帮助器方法。

回答

3

除了ApplicationHelper之外,视图还可以访问特定于视图的助手。由于这是您的产品相关视图,因此只能访问ApplicationHelper + ProductsHelper。因此,解决方案是将此方法移至ProductsHelper或ApplicationHelper。

+0

感谢@MarcusTres,今天学到了一些新东西:)我发现了另外两个选项对我也有效,请参阅[我的答案](http://stackoverflow.com/a/29734454/3519981)。 – PSR

1

我发现了两个办法,使这些方法提供给其他的意见,以及:描述我controllers/myengine/application_controller.rb文件https://stackoverflow.com/a/9641149/3519981

或者通过包括helper :all

通过建立在我的/my_engine/lib/my_engine/engine.rb文件的初始化这里所描述这里:https://stackoverflow.com/a/1179900/3519981

注意两者都会使主应用程序中的所有助手都可用。对我而言,这不是一个问题(目前)。

相关问题