David
David

Reputation: 71

Declare the same model twice - Rails

So, I have two models and I am trying to declare each of the models twice, for some purposes. for some reason, the second model cannot declare again, and when I am running this line - Foo2.first.bar2 , Im getting an error: undefined method 'bar2'

The first model, however, running perfectly: Foo1.first.bar1

Any help will much appreciated. Thanks, David

My models look like:

In my appname/app/models/foo1.rb:

class Foo1 < ActiveRecord::Base
    def bar1
        puts 'bar'
    end
end

In my appname/app/models/foo2.rb:

class Foo2 < ActiveRecord::Base
    def bar2
        puts 'bar2'
    end
end

In my appname/config/initializers/main.rb :

require "main_classes"

In my appname/lib/main_classes.rb :

class Foo1 < ActiveRecord::Base
    attr_accessible :foo1_name
end

class Foo2 < ActiveRecord::Base
    attr_accessible :foo2_name
end

When I remove the required line, it runs perfectly .. why ?

/========== updated =============/

I have 3 tables : Tables, Columns, Funcs.

In Tables I have the table names, In Columns, the columns names, types etc. And in Funcs the Tables funcionality.

The code in appname/app/func.rb :

class Func < ActiveRecord::Base
    def foo
        puts 'bar'
    end
end

In appname/config/initializers/main.rb :

require "main_classes"

In appname/lib/main_classes.rb:

Table.find_each do |t|
    t.columns.where(accessible: true).find_each do |c|
        eval "class #{t.name.classify} < ActiveRecord::Base ;          attr_accessible :#{c.name.to_sym} ; end ;"
    end
end

The code Func.first.foo raise undefined method 'bar'

When I remove the required line, it runs perfectly .. why ?

Upvotes: 0

Views: 239

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230346

When I remove the required line, it runs perfectly .. why ?

As I have mentioned in comments, the answer is - rails autoloading mechanism.

When you reference a class (Func in your case), one of two things happen:

  • if class with such name is loaded, it is returned
  • if it is not loaded, rails tries to find it by looking for func.rb in its $LOAD_PATH directories. If it's still not found there, LoadError is raised.

In your case, Func is defined at application startup (when initializers run). So when you later do Func.first.foo, that plain Func with a couple of attr_accessible is returned. Your app/models/func.rb won't ever be evaluated.

Possible solution: configure eager loading of classes (http://guides.rubyonrails.org/configuring.html).

Upvotes: 1

Related Questions