LoadError Unable to autoload constant Message

pwz2000 picture pwz2000 · Jun 20, 2014 · Viewed 67k times · Source

In my app; when I submit form, I get this error:

LoadError at /questions
Unable to autoload constant Message, expected /app/models/message.rb to define it

It points to the create action in the Questions controller:

@message = current_user.messages.new(:subject => "You have a question from #{@question.sender_id}"`

Message model:

class Mailboxer::Message < ActiveRecord::Base
  attr_accessible :notification_id, :receiver_id, :conversation_id
end

Answer

kik picture kik · Jun 24, 2014

By convention in rails (and this is enforced by autoloader), file paths should match namespaces.

So, if you have a Mailboxer::Message model, it should be in app/models/mailboxer/message.rb.

Additionally, you probably have autoloader kicking in when trying to load a Message class (my guess is that it happens from within ActAsMessageable). It looks for a message.rb file in load path, find it in app/model/ and thus load that file so it can find the Message class.

Problem is, it doesn't find a Message class in that file, only a Mailboxer::Message class (which is radically different). This is why it throws "Unable to autoload constant Message, expected /app/models/message.rb to define it".

To fix that, create directory app/models/mailboxer/ and put Mailboxer::Message in it.