2016-03-30 37 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

相關問題