Hi there I have 3 files in rails as follows:
1)Located at “app/controller/listings_controller.rb”
class ListingsController < ApplicationController
def index
#Construct kd Tree in memory
@tree = Listing.constructKDTree;
@tree.inspect
end
2) Located at app/models/listing.rb
require 'kd_tree.rb'
class Listing < ActiveRecord::Base
def constructKDTree
@contents = self.all
@kdTree = KDTree.new(@contents)
end
3) Located at app/models/kd_tree.rb
class KDTree
def initialize (db_listings)
'Initializing Tree'
end
end
Now I’m trying to test the method implementation for constructKDTree so I went to my rails console and tried the following commands:
1.9.2-p290 :001 > @lc = ListingsController.new
=> #<ListingsController:0x00000104f3e288 @_routes=nil, @_action_has_layout=true, @_headers={"Content-Type"=>"text/html"}, @_status=200, @_request=nil, @_response=nil>
1.9.2-p290 :002 > @lc.index
But I get this error:
NoMethodError: undefined method `constructKDTree' for #<Class:0x00000104b1f760>
from /Users/AM/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-3.2.1/lib/active_record/dynamic_matchers.rb:50:in `method_missing'
from /Users/AM/Documents/RailsWS/cmdLineWS/Businesses/app/controllers/listings_controller.rb:20:in `index'
from (irb):2
from /Users/AM/.rvm/gems/ruby-1.9.2-p290/gems/railties-3.2.1/lib/rails/commands/console.rb:47:in `start'
from /Users/AM/.rvm/gems/ruby-1.9.2-p290/gems/railties-3.2.1/lib/rails/commands/console.rb:8:in `start'
from /Users/AM/.rvm/gems/ruby-1.9.2-p290/gems/railties-3.2.1/lib/rails/commands.rb:41:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'
What am I doing wrong?
You defined
constructKDTreeas an instance method onListing. Thus the method is only available on instances of the class but nit the class itself.Depending on what you actually want to achieve, you can make the method a class method like it’s done in the following code, or you could create a new instance of the
Listingclass and call the method on the instance.However looking at the code you have there, you probably want to do the latter and create a new instance of the class: