0

I am using a rails blogging engine called Monologue. I would like one of the engines's models to have a belongs_to and has_many relationship with my main apps model. A user (author) can have many posts, and a post belongs to an author (User Model). I tried namespacing the model in the class_name but it did is still searching for the model within the engine.

Error

NameError: uninitialized constant Monologue::Post::MyApp::User

post.rb

class Monologue::Post < ActiveRecord::Base
  belongs_to :author, :class_name => "MyApp::User", :foreign_key => "author_id"
end

user.rb

class User < ActiveRecord::Base
  has_many :posts, :class_name => "Monologue::Post", :foreign_key => "author_id"
end

Schema

create_table "monologue_posts", force: true do |t|
  t.integer  "author_id"
end

I got this far using: Creating a belongs_to relationship with a model from the main app from an engine model

Community
  • 1
  • 1
MicFin
  • 2,431
  • 4
  • 32
  • 59

1 Answers1

0

NameError: uninitialized constant Monologue::Post::MyApp::User

You need to fix the class name of user.rb to MyApp::User

class MyApp::User < ActiveRecord::Base
  has_many :posts, :class_name => "Monologue::Post", :foreign_key => "author_id"
end
Pavan
  • 33,316
  • 7
  • 50
  • 76
  • Will I have to adjust every instance of User in my app's code to MyApp::User? – MicFin Oct 19 '15 at 16:42
  • @MicFin You have defined the class name in `Monologue::Post` of `user.rb` like `:class_name => "MyApp::User"`, so you need to change the class name of `user.rb` as well – Pavan Oct 19 '15 at 16:45
  • Renaming the User class breaks rails active support /Users/Mike/.rvm/gems/ruby-2.1.5/gems/activesupport-4.1.1/lib/active_support/dependencies.rb:481:in `load_missing_constant': Unable to autoload constant User, expected /Users/Shared/code/kindrdfood/RecRm/app/models/user.rb to define it (LoadError) – MicFin Oct 19 '15 at 16:47
  • @MicFin Try putting the file `user.rb` should be in `app/models/my_app` too – Pavan Oct 19 '15 at 16:52
  • I should have two copies of my user.rb? One in app/models/user.rb and one in app/models/my_app/user.rb? That seems like too much duplicative code for this. – MicFin Oct 19 '15 at 16:56
  • @MicFin No! Try moving the file `user.rb` to `app/models/my_app` and check. – Pavan Oct 19 '15 at 16:57
  • Thank you. I did that and it ended up breaking active_admin and I believe it would complicate other things. Your answer is correct for the amount of the problem I posted but there are other complications so I've decided to just use a foreign key on my app's model and reference the user in the engine. Thank you for your help. I will mark as correct for next user in similar situation. – MicFin Oct 19 '15 at 17:11