finiteloop
finiteloop

Reputation: 4496

Rails model with other model as instance variable

I am building a Rails application that contains Developers who have Applications. Both Developers and Applications are objects whose contents come from an external API. Thus, both of these models are hand-written and do not take advantage of ActiveModel, ActiveResource, etc.

I am trying to determine how to instantiate the Application object as an instance variable of the Developer object.

I have the following code within my Developer.initialize() function:

@apps = Array.new
data['applications'].each do |app|
  @apps << Application.new(app)
end

The code is fairly self explanatory. Both developer.rb (which is where Developer is defined) and application.rb (which is where Application is defined) lie in the app/models directory. My developers controller instantiates a Developer object by calling Developer.new.

The line of code within the do block produces the following error:

uninitialized constant Developer::Application
app/models/developer.rb:24:in `initialize'
app/controllers/developers_controller.rb:11:in `new'
app/controllers/developers_controller.rb:11:in `show'

So it looks like Rails is trying to instantiate a Developer::Application, whereas I want to instantiate the Application object defined in application.rb within the app/models directory. Is there some way for this to be done?

Upvotes: 1

Views: 151

Answers (1)

finiteloop
finiteloop

Reputation: 4496

You have to require the necessary files. In my case, from within the Developer class, I needed the following line: require 'application.rb' and everything worked fine.

Upvotes: 1

Related Questions