Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialJiaming Zhang
10,170 PointsQuestions About Helper Module in Rails
I tried to create a helper module for my Rails application. I included the module in my model, created some new method using functions from the module and it works in the controller. However, it raise an exception when I try to view a page who use the model.
Here is the details:
First, I created the helper module. The file name is "lib/data_query.rb".
module DataQuery
def foo
return 42
end
end
Second, I modified the file "config/application.rb"
config.autoload_paths += %W(#{config.root}/lib/)
The model which will be using this module is called App. I included the module and built new methods on the module function
class App < ActiveRecord::Base
include DataQuery
# ...... other method ...
def bar
# function from DataQuery
return foo
end
end
I run it in the Rails console and it works.
App.new.foo # it works
However, I have a controller and view called Report. In report#index, I have an instance variable called
def index
@app = App.find(1)
end
When I atttempted to open the view, an exception shows up: "uninitialized constant App::DataQuery"
Any suggestions?
2 Answers
Maciej Czuchnowski
36,441 PointsI'm not sure if this will help, but try writing those model methods as def.self.method_name
instead of just def method_name
.
Samuel Johnson
9,152 PointsJust a side note but not sure exactly what you are trying to achieve?
Are you trying to create a helper to available globally? or is this something limited to a number of views controlled by a controller because it seems you are using a regular ruby module similar to this post : Rails helper modules
it may be inside your controller for the view your talking about it doesn't have access to the module and needs to be included?
just a thought...
Samuel Johnson
9,152 PointsSamuel Johnson
9,152 Pointsi think you mean
def self.method_name
Maciej Czuchnowski
36,441 PointsMaciej Czuchnowski
36,441 PointsYup, my bad :)