2016-03-30 23 views
0

我试图提供一个接口来从电子表格文件“预加载”一个表。听起来很简单,但我正在恶作剧,作为一个完整的新手。我已经使用action_view helper asset_path在资产预编译之后找到文件,但似乎我没有正确包含helpers,因为我一直在为“#”取得“NoMethodError:未定义方法`asset_path'”。这里是我的模型代码:Rails:在模型中使用roo来加载表,不断得到:NoMethodError:未定义的方法`asset_path'

require 'rubygems' 
require 'roo' 
require 'action_view' 

class Item < ActiveRecord::Base 
    include ActionView::Helpers 
    validates :description, presence: true, length: { maximum: 240 } 
    validates :category, presence: true 
    has_many :interests 
    has_many :members, through: :interests 
end 

def populate_items_table 
    from_file = asset_path("item_listing.ods") 
    original_list = Openoffice.new(from_file) 
    original_list.default_sheet = original_list.sheets.first 
    headers = original_list.row(1) 
    ... 
end 

我将不胜感激,如果有人能指出我要去的地方错在这里。另外,我是在“Rails方式”中讨论这个问题吗?这种代码应该放在模型还是其他地方?我在其他地方猜测,否则适当的帮手可能已经被定义了?

这里堆栈上也有类似的问题,例如, 1,但答案似乎没有任何不同,我在做什么。

@shishir:这里是包括特定的模块当所述堆栈跟踪的建议:

ERROR["test_should_reload_items_table", ItemsControllerTest, 2016-03-22 08:43:53 +0000] test_should_reload_items_table#ItemsControllerTest (1458636233.20s) NoMethodError: NoMethodError: undefined method asset_path' for #<ItemsController:0x000000097cb308> app/models/item.rb:14:in populate_items_table' app/controllers/items_controller.rb:67:in reload' test/controllers/items_controller_test.rb:53:in block in ' app/models/item.rb:14:in populate_items_table' app/controllers/items_controller.rb:67:in reload' test/controllers/items_controller_test.rb:53:in `block in '

回答

0

asset_path在::的ActionView助手:: AssetUrlHelper这是一个模块定义的。 使用

include ActionView::Helpers::AssetUrlHelper 

,而不是

include ActionView::Helpers 
+0

我以前试过,并得到“ActionView :: Template :: Error:未定义的方法错误'为零:NilClass”。我认为通过包括所有帮助者,我更可能包含更具体模块所依赖的所有东西? – FBtLL

+0

可以将堆栈跟踪粘贴到nil类的错误? – Shishir

+0

我的歉意,我冲进了那个回应。 ActionView :: Template :: Error没有关系,我试图在其他领域取得进展,并且这个错误与尚未构建的东西有关......我现在已经发布了来自模型代码测试的更正跟踪,它仍然在报告undefined_method。 – FBtLL

0
class Item < ActiveRecord::Base 
    include ActionView::Helpers 
    validates :description, presence: true, length: { maximum: 240 } 
    validates :category, presence: true 
    has_many :interests 
    has_many :members, through: :interests 

    def populate_items_table 
     from_file = asset_path("item_listing.ods") 
     original_list = Openoffice.new(from_file) 
     original_list.default_sheet = original_list.sheets.first 
     headers = original_list.row(1) 
     ... 
    end 

end 

如果我理解正确的话,如果它是不是类里面的功能将无法正常工作。

无论如何,您需要以这样的方式包含ActionView :: Helpers,以使其到达asset_path调用,它目前不会调用它(因为它在Class中分离,它与当前函数不同你已经声明。)

+0

现在我很困惑。你是什​​么意思,如果它不在课堂内,我的功能将不起作用?它在Item类中,不是吗?这就是我包括助手的地方。我应该如何包括帮手?我只是遵循其他人提交的类似问题的例子。 – FBtLL

相关问题