Search code examples
ruby-on-rails-4activerecordforeign-key-relationshiprails-modelsmonologue

Rails belongs_to has_many relationship, main app and engine


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


Solution

  • 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