Andy Harvey
Andy Harvey

Reputation: 12653

Is the name Application reserved within Rails?

I have an Application model in a Rails 4 app.

It is giving me some strange errors in tests, including

NoMethodError: undefined method `user_id=' for #<Application:0x007f851222d370>

and

ActiveModel::MissingAttributeError: can't write unknown attribute `user_id`

The model definitely has a user_id column. The migration looks like this:

....
t.references :user, index: true, foreign_key: true
...

and inspecting Application.column_names in the console reveals it to be there.

application.rb and user.rb both have the relevant belongs_to and has_many calls defined.

I'm scratching my head and the only thing I can think of is that the term Application behaves strangely in Rails. Is this the case? Or have I missed something obvious?

Upvotes: 0

Views: 180

Answers (2)

max
max

Reputation: 102016

Rails does not declare Application in the "top-level namespace". There is Rails.application and rails generates a ApplicationController by default.

However you will need to often need to explicitly use ::Application to avoid confusion with Rails::Application.

You don't even have to follow the Rails convention of extending ApplicationController.

However that said having a model named Application may be a bad idea since any poor sod who later has to work on your code will be very confused.

Upvotes: 2

Andrey Turkin
Andrey Turkin

Reputation: 719

It's a conflict with Rails::Application class or its subclass, defined in config/application.rb, I believe.

Upvotes: 0

Related Questions