0

我正在尝试提供一个界面来“预加载”电子表格文件中的表格。听起来很简单,但作为一个完全的新手,我正在接受恶劣的天气。在资产中预编译文件后,我使用 action_view 帮助器asset_path 来定位文件,但似乎我没有正确包含帮助器,因为我不断收到“NoMethodError:未定义的方法 `asset_path' for #”。这是我的模型代码:

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:这是包含建议的特定模块时的堆栈跟踪:

错误 ["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:inpopulate_items_table' app/controllers/items_controller.rb:67:in reload' test/controllers/items_controller_test.rb:53:inblock in ' app/models/item.rb:14:in populate_items_table' app/controllers/items_controller.rb:67:inreload' test/controllers/items_controller_test.rb:53:in `block in'

4

2 回答 2

0

asset_path is defined in ActionView::Helpers::AssetUrlHelper which is a module. use

 include ActionView::Helpers::AssetUrlHelper

instead of

 include ActionView::Helpers
于 2016-03-31T00:47:29.067 回答
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调用(因为它在类中隔离,该类当前与您声明的函数处于不同的范围内.)

于 2016-03-31T02:00:24.910 回答