ruby-on-railsactivemodelrails-modelsmailboxer

LoadError Unable to autoload constant Message


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

Solution

  • 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 the load path, finds it in app/model/ and thus loads 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 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.