Rails belongs_to has_many 关系,主要应用和引擎

Rails belongs_to has_many relationship, main app and engine

我正在使用一个名为 Monologue 的 rails 博客引擎。我希望其中一个引擎模型与我的主要应用程序模型具有 belongs_to 和 has_many 关系。一个用户(作者)可以有多个post,一个post属于一个作者(用户模型)。我尝试在 class_name 中为模型命名空间,但它仍在搜索引擎中的模型。

错误

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

架构

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

到目前为止我使用的是:Creating a belongs_to relationship with a model from the main app from an engine model

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

您需要将user.rbclass名称修改为MyApp::User

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