I'm trying to provide an interface to "pre-load" a table from a spreadsheet file. Sounds simple, but I'm making heavy weather of it, being a complete novice. I have used the action_view helper asset_path to locate the file after it is precompiled in assets, but it seems that I am not including the helpers properly, because I keep getting "NoMethodError: undefined method `asset_path' for #". Here is my model code:
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
I would be most grateful if anyone can point out where I am going wrong here. Also, am I going about this in the "Rails way"? Should this sort of code be in the model or somewhere else? I am guessing somewhere else, otherwise the appropriate helpers would probably already be defined?
There are similar questions on the stack here, e.g. 1 , but the answers don't seem to be any different to what I am doing.
@shishir: here is the stack trace when including the specific module as suggested:
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:inreload' test/controllers/items_controller_test.rb:53:in
block in ' app/models/item.rb:14:inpopulate_items_table' app/controllers/items_controller.rb:67:in
reload' test/controllers/items_controller_test.rb:53:in `block in '
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
If I understand correctly, your function won't work if it isn't inside the class.
Irrespective, you need to include ActionView::Helpers in such a way that it reaches the asset_path call, which it currently doesn't (as it is segregated in the Class, which is in a different scope currently to the function you've declared.)